主要是通过spring上下文获取交给spring管理的bean; 还是通过前面写过的文章案例 FactoryBean 的使用
类中通过@service注解初始化对象
Service("userService") public class UserService { private String userName="UserService命名小康康"; public UserService() { System.out.println(this); System.out.println("UserService初始化"); } private UserService(String userName) { this.userName = userName; } public static UserService getInstance(String userName){ return new UserService(userName); } public String say(String detail) { System.out.println("用户{"+userName+"} say{"+detail+"}"); return "say执行完毕"; } }通过
@Configuration public class FactoryBeanConfig { @Bean public UserServiceFactoryBean createUserFactoryBean (){ UserServiceFactoryBean bean = new UserServiceFactoryBean("createUserFactoryBean命名小康康"); System.out.println("createUserFactoryBean初始化"); return bean; } @Bean public UserService createUserService (){ UserService bean = UserService.getInstance("createUserService命名小康康"); System.out.println("createUserService初始化"); return bean; } } @RestController @RequestMapping("/factory") public class FactoryController { @Autowired private SpringAware springAware; @Autowired private UserServiceFactoryBean factoryBean; @Autowired private UserService userService; @Autowired private UserService createUserService; @Autowired private UserService createUserFactoryBean; @RequestMapping("/test") public String test() throws Exception{ System.out.println("///userService执行开始//"); String say = userService.say("注入的userService成功"); UserService getService = springAware.getBeanByName("userService"); say = getService.say("SpringAware获取的的userService成功"); System.out.println("///userService执行结束//"); System.out.println("///createUserService执行开始//"); say = createUserService.say("注入的createUserService成功"); UserService getService1 = springAware.getBeanByName("createUserService"); say = getService1.say("SpringAware获取的的createUserService成功"); System.out.println("///createUserService执行结束//"); System.out.println("///createUserFactoryBean执行开始//"); say = createUserFactoryBean.say("注入的createUserFactoryBean成功"); UserService getService2 = springAware.getBeanByName("createUserFactoryBean"); say = getService2.say("SpringAware获取的的createUserFactoryBean成功"); System.out.println("///createUserService执行结束//"); /** * 上面都是直接获取的UserService * UserService createUserFactoryBean 是通过工厂UserServiceFactoryBean创建的 * 但是如果想拿到工厂类本身则通过ApplicationContext 获取的时间需要添加& */ System.out.println("///工厂类UserServiceFactoryBean执行开始//"); say = factoryBean.getObject().say("注入的createUserFactoryBean的UserServiceFactoryBean成功"); UserServiceFactoryBean getFactory = springAware.getBeanByName("&createUserFactoryBean"); getFactory.getObject().say("SpringAware获取的的UserServiceFactoryBean成功"); System.out.println("///工厂类UserServiceFactoryBean执行结束//"); return "执行完毕了"+say; } }