如何从spring容器中取出注入的对象 SpringContainerUtils

有时候我们需要在一个类中使用已经被注入spring容器的类(比如被包扫描的mapper接口,或者加了@Component注解的类)

但一个类要想使用spring容器的对象,一般需要声明对象,然后用@AutoWired注解,而这又要求当前类得被spring容器管理(被包扫描或者使用了@Component注解)

但我只是想用一个接口,我不想让当前类存入spring容器中,所以就有了标题的需求

 

因此可以使用下面的这个封装类,调用get方法即可

CComponent 
public class SpringContainerUti1s implements ApplicationContextAware 
private static ApplicationContext applicationContext , 
@Override 
public void setApp1icationContext (ApplicationContext applicationContext1) throws BeansException 
applicationContext —applicationContext1; 
getean { 
return applicationContext. getBean (clazz) ; 
public static

/**
 * 从容器中获取到bean对象
 */
@Component
public class SpringContainerUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext1) throws BeansException {
            applicationContext=applicationContext1;
    }

    public static <T> T getBean(Class<T> clazz){
        return applicationContext.getBean(clazz);
    }
}

这个工具类的底层原理其实就是依托了springIOC的代码

Appliætion this file 
beans xmlns="http://www. springframework. org/schema/beans- 
xsi="http://www. w3_ org/2001/XMLSchema—instance 
xsi: schemaLocation=-http://www. springframework. org/schema/beans http://www. springframework 
. org/schema/beans/spring—beans. 
<bean class— com- jovasm. ioc. service. impl. 
< / beans) 
:/spring 
new ClasspathXm1ApplicationContext( configLocation: -applicationContext. xml") : 
ClassPathXmlApplicationContext ac = 
getBean( name: "userService") ; 
User-Service user-Service

 

实际使用场景举例

import 
import 
import 
com. avasm. cym. ccmnon . I s . SpringConCainerUtiI 
org . springframework . mail . SimpleMaiIMessage ; 
org . springframework . mail . javamail . JavaMaiISender ; 
— public class AsyncFacCory { 
public static Runnable sendEmaiI (String email, String content) { 
Runnable runnable = O — > { 
System. out . print In (Thread. cmIIenCThread() . geCName ( ) ) ; 
JavaMai I Sende r bean 
. geCBean (JavaMaiISender . class) ; 
SimpleMaiIMessage simpleMaiIMessage 
new SimpleMaiIMessage ( ) ; 
simpleMaiIMessage . . 
simpleMaiIMessage . setTo (email) ; 
simpleMaiIMessage . setSubj ect ( 
simpleMaiIMessage . setTexC (content) ; 
bean. send (simpleMaiIMessage) ; 
return runnable ;

posted @ 2021-10-05 00:17  夏·舍  阅读(397)  评论(0编辑  收藏  举报