Spring Boot在普通类中注入Bean

Spring Boot在普通类中注入Bean

1:在Controller Service 等中,直接@ Autowired注入bean就好。
但在普通类中这样注入会提示null。
对于此类的bean的注入,可以implements ApplicationContextAware。

如下面:调用方式为:

UserService userservice = (UserService)
SpringContextUtils.getBean(UserService.class);



import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.stereotype.Component;

 

@Component

public class SpringContextUtils implements ApplicationContextAware {

 

   

   private static ApplicationContext applicationContext;

 

   @Override

   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

       this.applicationContext = applicationContext;

   }

 

   

   public static ApplicationContext getApplicationContext() {

       return applicationContext;

   }

 

   

   public static Object getBean(String name) {

       return getApplicationContext().getBean(name);

   }

 

   

   public static T getBean(Class clazz) {

       return getApplicationContext().getBean(clazz);

   }

 

   

   public static T getBean(String name, Class clazz) {

       return getApplicationContext().getBean(name, clazz);

   }

}

你可能感兴趣的:(spring,boot,spring,java)