Spring、实例化Bean的三种方法
2015-11-06 11:32
585 查看
1、使用类构造器进行实例化
测试代码:
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
PersonIService personIService=(PersonIService)ac.getBean("personIService");
personIService.helloSpring();
}
2、使用静态工厂实例化
public class BeanFactory {
public static PersonServiceImpl createPersonServiceImpl(){
return new PersonServiceImpl();
}
}
测试代码:
@Test
public void test3() {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
PersonIService personIService=(PersonIService)ac.getBean("personIService2");
personIService.helloSpring();
}
3、使用实例化工厂实例化
public class BeanFactory {
public PersonServiceImpl createPersonServiceImpl2(){
return new PersonServiceImpl();
}
}
测试代码:
@Test
public void test4() {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
PersonIService personIService=(PersonIService)ac.getBean("personIService3");
personIService.helloSpring();
}
<bean id="personIService" class="cn.server.impl.PersonServiceImpl" />
测试代码:
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
PersonIService personIService=(PersonIService)ac.getBean("personIService");
personIService.helloSpring();
}
2、使用静态工厂实例化
public class BeanFactory {
public static PersonServiceImpl createPersonServiceImpl(){
return new PersonServiceImpl();
}
}
<bean id="personIService2" class="cn.BeanFactory" factory-method="createPersonServiceImpl" />
测试代码:
@Test
public void test3() {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
PersonIService personIService=(PersonIService)ac.getBean("personIService2");
personIService.helloSpring();
}
3、使用实例化工厂实例化
public class BeanFactory {
public PersonServiceImpl createPersonServiceImpl2(){
return new PersonServiceImpl();
}
}
<bean id="beanFactory" class="cn.BeanFactory"/> <bean id="personIService3" factory-bean="beanFactory" factory-method="createPersonServiceImpl2" />
测试代码:
@Test
public void test4() {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
PersonIService personIService=(PersonIService)ac.getBean("personIService3");
personIService.helloSpring();
}
相关文章推荐
- 初识Spring4
- Spring、实例化Bean的三种方法
- 深入浅析Java反射机制
- Java通过webservice接口获取天气信息
- Spring 集成Quartz Scheduler 定时调度任务 Example
- Caused by: java.net.ConnectException: Connection timed out: connect||Caused by: com.mysql.jdbc.excep
- android 在 eclipse 中的 快捷键--亲测实用的
- Myeclipse 控制台 乱码
- springMVC文件转换问题
- ORM、JPA、Hibernate简单说明
- Spring和spring MVC,spring MVC和Strut2的区别
- Spring MVC实现CRM系统架构
- Java windows 64 机器配置32 位eclipse
- java可以使用计算日期的天数差,以下是详细代码:{转自百度知道....}
- 深入理解Java2:内省(Introspector)
- java、js处理科学计数法的问题
- Eclipse 出现Some sites could not be found. See the error log for more detail.错误 解决方法
- Eclipse+WebService开发案例
- Java并发编程:Lock
- Spring几种数据源的配置方法