码迷,mamicode.com
首页 > 编程语言 > 详细

【SpringBoot】在IOC之外的类中使用IOC内部的Bean

时间:2018-10-02 14:18:18      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:odi   ret   自己   member   ide   new   逻辑   row   ioc   

某些时候,某些类是不归IOC管的,如我们的一些Util,如何使用IOC中的Bean?

 

1、写一个SpringUtil类,该类用于操纵Spring的ApplicationContext

@Component的注解是需要的,该Util是要被Spring管理的。
@Component
public class SpringUtil implements ApplicationContextAware
{
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        if (SpringUtil.applicationContext == null)
        {
            SpringUtil.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext()
    {
        return applicationContext;
    }

    public static Object getBean(String name)
    {
        return getApplicationContext().getBean(name);
    }

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

    public static <T> T getBean(String name, Class<T> clazz)
    {
        return getApplicationContext().getBean(name, clazz);
    }
}

2、通过@Bean注解,返回一个Bean;

@Component
@Transactional
public class SysParamBusiness
{
    @Autowired
    private SysParamDao sysParamDao;
    
    public void modify(SysParamMO mo) throws LittleCatException
    {
        sysParamDao.modify(mo);
    }
    public String getValueByName(String name) throws LittleCatException
    {
        return sysParamDao.getValueByName(name).getValue();
    }
    public List<SysParamMO> getList() throws LittleCatException
    {
        return sysParamDao.getList();
    }
    
    @Bean(name="SysParamBusiness") 
    public SysParamBusiness getSysParamBusiness()
    {
        return new SysParamBusiness();
    }
}

 

3、在我们自己的Util中使用

 

public class SysParamUtil
{
    public static String PARAM_NAME_MEMBER_ENABLE_DAYS = "member_enable_days";
    
    private static final SysParamBusiness sysParamBusiness = (SysParamBusiness) SpringUtil.getBean("SysParamBusiness");

    public static String getValueByName(String name) throws LittleCatException
    {
        return sysParamBusiness.getValueByName(name);
    }
}

 

注:

也可以这样使用(如果没有特殊逻辑,推荐使用这种方法):

private static final SysParamBusiness sysParamBusiness = SpringUtil.getBean(SysParamBusiness.class);

 

这样,第二步就可以省略了。

 

【SpringBoot】在IOC之外的类中使用IOC内部的Bean

标签:odi   ret   自己   member   ide   new   逻辑   row   ioc   

原文地址:https://www.cnblogs.com/njlittlecat/p/9736341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!