Spring some problem records

1. Inject beans in non-spring beans

        In a project, sometimes you need to create a new object yourself, or obtain a Spring Bean object in some util methods or properties, so as to complete some work, but because your new objects and util methods are not managed by Spring, If it is used directly on the property it depends on, @Autowiredan error that cannot be injected will be reported, or no error will be reported, but a null pointer exception will be reported when it is used. All in all, since it is not managed by the IoC container, it cannot be injected.

        Spring provides two interfaces: BeanFactoryAware and ApplicationContextAware, both of which inherit from the Aware interface. The following are the declarations of these two interfaces:

public class Startup implements ApplicationContextAware, ServletContextAware {

    private static Logger logger = Logger.getLogger(Startup.class);

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info(" service was setApplicationContext");
        this.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        Map<String, T> beans = applicationContext.getBeansOfType(clazz);
        return Lists.newArrayList(beans.values()).get(0);
    }

    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

    In non-spring beans, the bean can be obtained through the static method Startup.getBean().

2. Inject static class variables

    It is an extension of the first question. When encapsulating some tool classes, and the current tool class is a spring bean, the tool classes are generally statically typed. In addition to injecting beans through the first method, can you use @AutoWire to As for injection, in fact, this scene is still a bit problematic. It is actually not necessary for the tool class to be registered as a bean, but if you have to do this, you can inject it through @PostConstruct + @AutoWire:

@Component  
public class StaticUtils{  
    @Autowired  
    private static AaService service;  
  
    private static StaticUtils staticUtils; 

    @PostConstruct  
    public void init() {  
        staticUtils= this;  
        staticUtils.service= this.service; //把类变量赋值到实例变量上
    }  
  
}  

Another way is to inject through the set method:

@Component  
public class StaticUtil {  
  
    private static AaService service;  
      
    @Autowired  
    public void setService(AaService service) {  
        StaticUtil.service= service;  
    }  
}  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325024495&siteId=291194637