在静态方法中使用spring注入的类

重点:

@Component 使用在类上实例化类到Spring容器中
@Autowired 使用在需要Spring注入的bean上用于Spring注入
@PostConstruct 使用在方法上,用于在服务器加载Servlet的时候运行

Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

思路:

通过在类中创建一个静态的实例,在调用@PostConstruct注解对应的方法时,将静态实例中需要被Spring注解的bean赋值为@Autowired注解的,然后在静态方法中使用被赋值后的静态的实例

案例:

ILdapConfigDao:数据库操作类
LdapConfig:查询返回的对象

@Component
public class MyLdapTemplate{
 	@Autowired
    ILdapConfigDao iLdapConfigDao;

    private static MyLdapTemplate mainLdapTemplate;

    @PostConstruct
    public void init(){
        mainLdapTemplate=this;
        mainLdapTemplate.iLdapConfigDao=this.iLdapConfigDao;
    }
    
	public static MyLdapTemplate builder(){
        return mainLdapTemplate;
    }

	public static LdapConfig getConfig(){
       return mainLdapTemplate.iLdapConfigDao.getById("1");
    }
}

使用时

MyLdapTemplate template= MyLdapTemplate.builder();
log.info(template.getConfig().toString());
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值