Java Implements Normal Class Injection into service Objects

  • 2021-11-01 03:28:45
  • OfStack

Common class injects service objects

Find a lot of ways, whether it's adding @ Component or writing a tool class to implement ApplicationContextAware, it's always null.

Finally, use these two lines of code to solve:


WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
DailySurveyService service = (DailySurveyService) context.getBean("dailySurveyService");

How the common class of spring injects service, dao

In web projects managed by spring, such as Struts and spring projects, the defined service can be directly used in Struts after configuration.

However, if you want to use service or dao in a common tool class, you will report a null pointer, because this common Java class is not managed by spring, and you cannot use service injected by spring.

Let's talk about a method below, so that ordinary tool classes can also use service.

Define 1 class SpringTool


/** 
 *  You can get it in a common tool class through this class spring Managed bean 
 * @author wolf 
 * 
 */  
public final class SpringTool implements ApplicationContextAware {  
    private static ApplicationContext applicationContext = null;  
  
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
        if (SpringTool.applicationContext == null) {  
            SpringTool.applicationContext = applicationContext;  
            System.out.println(  
                    "========ApplicationContext Configuration succeeded , In ordinary classes, you can call ToolSpring.getAppContext() Get applicationContext Object ,applicationContext="  
                            + applicationContext + "========");  
        }  
    }  
  
    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
  
    public static Object getBean(String name) {  
        return getApplicationContext().getBean(name);  
    }  
}  

Then add this class to the configuration file of spring


<bean class="app.util.spring.SpringTool"/>

Then you can, you can in any one common tool class, according to the spring bean id configured in spring,

Got this injected object


import app.util.spring.SpringTool;  
public class Test {  
      
    public void print() {  
        ArticleService articleService = (ArticleService) SpringTool.getBean("articleService");  
        Article article = articleService.queryById(756);  
        System.out.println(article.getTitle());  
    }  
} 

Related articles: