Spring中的多例往单例里注入的方法

简介: Spring的prototype向singleton注入会有问题,具体见 Spring Bean的prototype无用的解决 除了这篇文章里介绍的方法(ApplicationContext .getBean和代理模式)以外,在java(Spring)领域还有集中其他的实现方式。

Spring的prototype向singleton注入会有问题,具体见

Spring Bean的prototype无用的解决

除了这篇文章里介绍的方法(ApplicationContext .getBean和代理模式)以外,在java(Spring)领域还有集中其他的实现方式。

这里我们说一下。

 

1. 使用Spring的ObjectFactory

如果本来的代码是这样的

    @Autowired
    private PrototypeBean bean;

 在单例里直接使用或者即使是在多例里面获取多次,这样拿到的也是同样的一个实例。

我们的状态bean就无效了。

可以改成这样

    @Autowired
    private ObjectFactory<PrototypeBean> bean;

 使用的时候调用getObject方法

bean.getObject()

 即可。

 

2. 使用java的JSR 330提出的Provider<T>

要引入jar包javax.inject

import javax.inject.Provider;

  使用上和前面的ObjectFactory类似,只是方法名称变成了get

 

在我看来Provider和ObjectFactory的区别就是Resource和Autowire的区别。

 

 

3.使用Spring的Lookup注解

import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;

@Component
public class MySingletonBean {

    public void showMessage(){
        MyPrototypeBean bean = getPrototypeBean();
      //do your 自己的逻辑
    }

    @Lookup
    public MyPrototypeBean getPrototypeBean(){
        //spring自己会覆盖该方法
        return null;
    }
}

 这样不用注入一个属性,但是要增加一个返回null的方法。

 

 

目录
相关文章
|
1月前
|
XML Java 开发者
Spring Boot中的bean注入方式和原理
Spring Boot中的bean注入方式和原理
44 0
|
1月前
|
缓存 Java API
【云原生】Spring Cloud Gateway的底层原理与实践方法探究
【云原生】Spring Cloud Gateway的底层原理与实践方法探究
|
1月前
|
存储 NoSQL Java
Spring Boot统计一个Bean中方法的调用次数
Spring Boot统计一个Bean中方法的调用次数
32 1
|
30天前
|
Java Spring
使用JDBCTemplate实现与Spring结合,方法公用 ——测试(EmpDaoImplTest)
使用JDBCTemplate实现与Spring结合,方法公用 ——测试(EmpDaoImplTest)
8 0
|
7天前
|
JSON Java 数据库连接
属性注入掌握:Spring Boot配置属性的高级技巧与最佳实践
属性注入掌握:Spring Boot配置属性的高级技巧与最佳实践
14 1
|
30天前
|
Java Spring
使用JDBCTemplate实现与Spring结合,方法公用 ——Emp实现类(EmpDaoImpl)
使用JDBCTemplate实现与Spring结合,方法公用 ——Emp实现类(EmpDaoImpl)
8 0
|
30天前
|
Java Spring
使用JDBCTemplate实现与Spring结合,方法公用 ——共用实现类(BaseImpl)
使用JDBCTemplate实现与Spring结合,方法公用 ——共用实现类(BaseImpl)
10 1
|
30天前
|
Java Spring
使用JDBCTemplate实现与Spring结合,方法公用 ——接口(BaseDao)
使用JDBCTemplate实现与Spring结合,方法公用 ——接口(BaseDao)
9 0
|
30天前
|
Java Spring
使用JDBCTemplate实现与Spring结合,方法公用
使用JDBCTemplate实现与Spring结合,方法公用
7 0
|
1月前
|
Java Spring 容器
【Spring源码】单例创建期间进行同步可能会导致死锁?
通过这个标题我们就可以思考本次的阅读线索了,看起来可以学到不少东西。1. 旧代码的死锁是怎么产生的。2. 贡献者通过改变什么来解决本次PR的问题呢?而阅读线索2的答案也显而易见,就是上文提到的通过后台线程来创建Micrometer单例...
41 3