结合自定义注解的 spring 动态注入
MyController自定义注解:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyController { String muv() default ""; }
初始化注入的UserServcie:
@Service(value = "userService") public class UserService { public String doService(String co) { return ("---我是spring注入的do service方法---"); } }
根据自定义注解批量动态注入的MyController1,2同:
@MyController public class MyController1 { public String getRes() { return "(我是被动态注入的"+this.getClass().getName()+")"; } }
动态注入的UserController:
public class UserController { private UserService userService; // public UserService getUserService() { // return userService; // } /** * 这个是必须的 * @param userService */ public void setUserService(UserService userService) { this.userService = userService; } public String toAction(String content){ System.out.println("我是动态注册的UserController的toAction方法,开始调用初始注入的userService.doService方法"); String res = userService.doService(content); MyController1 myController1 = (MyController1)SpringContextUtil.getBean(MyController1.class); MyController2 myController2 = (MyController2)SpringContextUtil.getBean(MyController2.class); return res + content + myController1.getRes() + myController2.getRes(); } }
springboot主函数:
@SpringBootApplication public class DemoSpringbootApplication { public static void main(String[] args) { ApplicationContext applicationContext = SpringApplication.run(DemoSpringbootApplication.class, args); SpringContextUtil.setApplicationContext(applicationContext); //将applicationContext转换为ConfigurableApplicationContext ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) SpringContextUtil.getApplicationContext(); DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory(); // 通过BeanDefinitionBuilder创建bean定义 BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(UserController.class); // 设置属性userService,【必须有setter】,此属性引用已经定义的bean:userService,这里userService已经被spring容器管理了. beanDefinitionBuilder.addPropertyReference("userService", "userService"); // 注册bean defaultListableBeanFactory.registerBeanDefinition("userController", beanDefinitionBuilder.getRawBeanDefinition()); System.out.println("开始根据自定义注解MyController动态注入"); Set<Class<?>> set = ClassUtil.getClassesController(); System.out.println("共 " + set.size() + "个类符合自定义注解"); for(Class<?> cl : set) { BeanDefinitionBuilder beanDefinitionBuilderAno = BeanDefinitionBuilder.genericBeanDefinition(cl); defaultListableBeanFactory.registerBeanDefinition(cl.getName(), beanDefinitionBuilderAno.getRawBeanDefinition()); System.out.println("注入成功 " + cl.getName()); } UserController userController = (UserController) SpringContextUtil.getBean("userController"); String res = userController.toAction("入参"); System.out.println(res); } }
遍历包,扫描自定义注解的类,参考:
参考: