bean实例化的三种配置,Spring的托管方式不同
- 新建一个Java项目,在项目中新建一个lib目录,往lib目录中导入以下几个架包
然后在lib目录上右键选择Build Path将其导入。 - 在src中新建一个test包,在包中新建一个C.java和test.java,在src中新建一个beans.xml文件,在beans.xml文件中写入下面这段代码,我们主要是在这段代码中操作。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>
<!-- ... -->
</beans>
- 1.beans实例化的第一种方式:调用构造方法
- 配置这样写
- <bean id="c " class="test.C"/ >
2.已经采用了工厂模式开发,但是不改动代码,如何配置bean
- <bean id="factory" class="test.factory"></bean>
- <bean id="E" factory-bean="factory" factory-method="getEInstance"></bean>
3.已经采用静态工厂模式开发,那么不改动代码如何配置bean
<bean id="k" class="test.StaticFactory" factory-method="getKInstance"/>
3.我们在beans.xml调用构造方法文件中写入以下代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="c" class="test.C"></bean>
</beans>
4.进入我们新建的C.Java文件。我们在里面Source一个空的构造方法,在书写一个新的sayHello方法
public class C {
public C() {
System.out.println("C 被实例化了");
}
public void saHello() {
System.out.println("Hello");
}
}
5.进入test.Java文件中编写
package test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource resource = new ClassPathResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
C c1 = (C) factory.getBean("c");
System.out.println(c1);
}
}