Spring实践第二天(创建对象的三种基本方式)
说明
昨天已经采用构造方法建立了一个项目并测试成功,
今天的项目实践如果看不懂就请参考我昨天实践写的博文:
入门小白,请多指教!
第一种方法:采用构造方法的方式
1.只在applicationContext.xml中配置bean即可:
<!-- 管理 bean --> <!-- 方式 1 :采用的构造方法方式来创建 --> <bean id="UserService" class="com.nenu.service.impl.UserServiceImpl"> </bean>
2.测试:
@Test public void iocTest(){ //1.获取容器实例 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.通过容器对象获取里面管理的bean UserService userService = (UserService) context.getBean("UserService"); //3.执行 userService.add(); }
第二种方法:采用静态工厂的方式来创建实例
1.新建静态工厂UserServiceStaticFactory:
package com.nenu.factory; import com.nenu.service.UserService; import com.nenu.service.impl.UserServiceImpl; public class UserServiceStaticFactory { private static UserService userService = new UserServiceImpl(); public static UserService getInstance(){ return userService; } }
2.在applicationContext中配置:
<!-- 方式 2 :采用静态工厂的方式来创建实例 --> <bean id="UserServiceByStaticFactory" class="com.nenu.factory.UserServiceStaticFactory" factory-method="getInstance"> </bean>
3.测试:
@Test public void staticFactoryTest(){ //1.获取容器实例 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.通过容器对象获取里面管理的bean UserService userService = (UserService) context.getBean("UserServiceByStaticFactory"); //3.执行 userService.add(); }
第三种方法:采用工厂的方式来创建实例
1.创建静态工厂UserServiceFactory:
package com.nenu.factory; import com.nenu.service.UserService; import com.nenu.service.impl.UserServiceImpl; public class UserServiceFactory { private UserService userService = new UserServiceImpl(); public UserService getInstance(){ return userService; } }
2.在applicationContext中配置:
<!-- 方式 3 :采用工厂的方式来创建实例--> <!-- 3.1 先声明工厂--> <bean id="UserServiceFactory" class="com.nenu.factory.UserServiceFactory"/> <!-- 3.2 创建实例,通过工厂方式创建--> <bean id="UserServiceByFactory" factory-bean="UserServiceFactory" factory-method="getInstance"> </bean>
3.测试:
@Test public void FactoryTest(){ //1.获取容器实例 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.通过容器对象获取里面管理的bean UserService userService = (UserService) context.getBean("UserServiceByFactory"); //3.执行 userService.add(); }