spring
1、bean配置的三种方式
(1)使用@Bean注解
package mybean; public class MyBean { private String name = "大法师"; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package mybean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MySpring { @Bean public MyBean make() { return new MyBean(); } }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); MyBean myBean = (MyBean) context.getBean("make"); System.out.println(myBean.getName());//大法师 }
applicationContext.xml中配置<context:component-scan base-package="mybean"/>
(2)使用XML配置bean
package mybean; public class Animal { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Animal animal = (Animal)context.getBean("animal"); System.out.println(animal.getName());//小猫 }
applicationContext.xml中配置 <bean id="animal" class="mybean.Animal"> <property name="name" value="小猫"></property> </bean>
(3)使用注解
package mybean; import org.springframework.stereotype.Component; @Component public class MyHome { public void play() { System.out.println("这是我家"); } public void run() { System.out.println("这不是我家"); } }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); MyHome myHome = (MyHome)context.getBean("myHome"); myHome.play();//这是我家 }
applicationContext.xml中配置<context:component-scan base-package="mybean"/>
2、bean实例化的三种方式
(1)普通构造方法创建
package mybean; public class User { public void working(){ System.out.println("工作少年"); } }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User)context.getBean("user"); user.working();//工作少年 }
applicationContext.xml中配置 <bean id="user" class="mybean.User"> </bean>
(2)静态方法创建
package mybean; public class UserFactory { public static User getInstance() { return new User(); } }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User)context.getBean("user"); user.working();//工作少年 }
applicationContext.xml中配置 <bean id="user" class="mybean.UserFactory" factory-method="getInstance"> </bean>
(3)实例工厂创建
package mybean; public class UserFactory { public User getUser() { return new User(); } }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User)context.getBean("user"); user.working();//工作少年 }
applicationContext.xml中配置 <bean id="userFactory" class="mybean.UserFactory"></bean> <bean id="user" factory-bean="userFactory" factory-method="getUser"> </bean>