2017-10-20 67 views
0

我在类和接口之下创建了,但原型bean构造函数没有被调用。我正在使用@Lookup来创建原型范围的bean。无法使用@Lookup注解在单例bean中的原型范围中自动装入bean

public interface IProtoTypeBean {} 

@Component 
@Scope(value = "prototype") 
public class ProtoTypeBean implements IProtoTypeBean { 

    public ProtoTypeBean() { 
     super(); 
     System.out.println("ProtoTypeBean"); 
    } 
} 

@Component 
public class SingleTonBean { 

    IProtoTypeBean protoTypeBean = getProtoTypeBean(); 

    @Lookup 
    public ProtoTypeBean getProtoTypeBean(){ 
     return null; 
    } 

    public static void main(String[] args) { 
     ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class); 
     SingleTonBean s1 = ctx.getBean(SingleTonBean.class); 
     IProtoTypeBean p1 = s1.protoTypeBean; 
     SingleTonBean s2 = ctx.getBean(SingleTonBean.class); 
     IProtoTypeBean p2 = s2.protoTypeBean; 
     System.out.println("singelton beans " + (s1 == s2)); 

     // if ProtoTypeBean constructor getting called 2 times means diff objects are getting created 
    } 

} 

回答

0

更改您的代码下面的步骤

@Component("protoBean") 
@Scope(value = "prototype") public class ProtoTypeBean implements IProtoTypeBean { 

而且

@Lookup(value="protoBean") 
public abstract ProtoTypeBean getProtoTypeBean(); 
+0

感谢,但没有奏效,我应该在哪里定义抽象getProtoTypeBean方法。 –

+0

更新getProtoTypeBean()并将其抽象为 – Mudassar

+0

我应该把它放在另一个抽象类 –

0

我建议使用原型提供商

添加行家依赖

<dependency> 
     <groupId>javax.inject</groupId> 
     <artifactId>javax.inject</artifactId> 
     <version>1</version> 
    </dependency> 

然后提两个班由Spring

ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class, ProtoTypeBean.class); 

进行管理,这里是供应商使用

@Component 
    public class SingleTonBean { 

    @Autowired 
    private Provider<IProtoTypeBean> protoTypeBeanProvider; 

    public IProtoTypeBean getProtoTypeBean() { 
     return protoTypeBeanProvider.get(); 
    } 

    public static void main(String[] args) { 
     ApplicationContext ctx = new AnnotationConfigApplicationContext(SingleTonBean.class, ProtoTypeBean.class); 
     SingleTonBean s1 = ctx.getBean(SingleTonBean.class); 
     IProtoTypeBean p1 = s1.getProtoTypeBean(); 
     SingleTonBean s2 = ctx.getBean(SingleTonBean.class); 
     IProtoTypeBean p2 = s2.getProtoTypeBean(); 
     System.out.println("singleton beans " + (s1 == s2)); 
     System.out.println("prototype beans " + (p1 == p2)); 
    } 
} 
+0

请让我知道是否有任何使用提供程序的优势,而不是查找注释 –

+0

@VikrantChaudhary,恕我直言,供应商是使用更清洁技术。有一个由Spring自动装配的工厂,它有get()方法创建新的prototype bean。相反,查找方法返回null,尽管它将被Spring重写。 –

+0

谢谢安德烈.. –

相关问题