Spring三种实例化方式
程序员文章站
2022-05-23 18:19:24
...
Spring容器支持两种格式的配置文件.properties .xml这两种配置文件
在面向对象的程序中,想要使用某个对象,就需要先实例化这个对象。同样,在Spring中,要想使用容器中的Bean,也需要实例化Bean。实例化Bean有三种方式,分别为构造器实例化、静态工厂方式实例化和实例工厂方式实例化(其中最常用的是构造器实例化)
1.构造器实例化
public class InstanceTest1 {
public static void main(String[] args) {
String xmlPath = "com/cxit/instance/constructor/beans1.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
Bean1 bean = (Bean1) applicationContext.getBean("bean1");
System.out.println(bean);
}
}
配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="bean1" class="com.cxit.instance.constructor.Bean1" />
</beans>
2.静态工厂实例化
public class InstanceTest2 {
public static void main(String[] args) {
String xmlPath ="com/cxit/instance/static_factory/beans2.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
System.out.println(applicationContext.getBean("bean2"));
}
public class MyBean2Factory {
public static Bean2 createBean(){
return new Bean2();
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id = "bean2" class = "com.cxit.instance.static_factory.MyBean2Factory"
factory-method="createBean"
/>
</beans>
3.实例工厂实例化
public class InstanceTest3 {
public static void main(String[] args) {
String xmlPath = "com/cxit/instance/factory/beans3.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
System.out.println(applicationContext.getBean("bean3"));
}
}
public class MyBean3Factory {
public Bean3 createBean(){
return new Bean3();
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id = "myBean3Factory" class = "com.cxit.instance.factory.MyBean3Factory">
</bean>
<bean id = "bean3" factory-bean="myBean3Factory" factory-method="createBean">
</bean>
</beans>