关于将注射原型注入单身人士的问题,有人问过我。我很难回答,现在我正在努力研究这个。
我写过以下代码(pring boot)
bean 1:
@Service
@Scope(value = "prototype")
public class MyValidator {
}
bean 2:
@Service
public class ValidatorHolder {
@Autowired
MyValidator myValidator;
public MyValidator getMyValidator() {
return myValidator;
}
}
配置:
@SpringBootApplication
@Configuration
@ComponentScan("com.example.domain")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
ApplicationContext context = new AnnotationConfigApplicationContext(DemoApplication.class);
ValidatorHolder validatorHolder1 = (ValidatorHolder) context.getBean("validatorHolder");
ValidatorHolder validatorHolder2 = (ValidatorHolder) context.getBean("validatorHolder");
System.out.println("=====================================");
System.out.println(validatorHolder1.getMyValidator() == validatorHolder2.getMyValidator());
System.out.println("=====================================");
}
}
此代码重新生效。
正如我在阅读article link时所理解的那样 可以配置为返回false。
我的代码怎么办? (不含xml)
我试着像文章一样重写代码:
<bean id="validatorHolder" class="com.example.domain.ValidatorHolder">
<property name="myValidator" ref="validator"/>
</bean>
<bean id="validator" scope="prototype" class="com.example.domain.MyValidator">
<!-- This instructs the container to proxy the current bean-->
<aop:scoped-proxy/>
</bean>
在main main方法中,我编写了以下代码:
ApplicationContext xmlContext = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
ValidatorHolder validatorHolder21 = (ValidatorHolder) xmlContext.getBean("validatorHolder");
ValidatorHolder validatorHolder22 = (ValidatorHolder) xmlContext.getBean("validatorHolder");
System.out.println("=====================================");
System.out.println(validatorHolder21.getMyValidator() == validatorHolder22.getMyValidator());
System.out.println("=====================================");
无论如何,我看到true
让Sean Patrick Floyd回答(范围代理,b))
我使用以下主要方法类:
@SpringBootApplication
@ComponentScan("com.example.domain")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
ApplicationContext context = new AnnotationConfigApplicationContext(DemoApplication.class);
ValidatorHolder validatorHolder1 = (ValidatorHolder) context.getBean("validatorHolder");
ValidatorHolder validatorHolder2 = (ValidatorHolder) context.getBean("validatorHolder");
System.out.println("=====================================");
System.out.println(validatorHolder1.getMyValidator() == validatorHolder2.getMyValidator());
System.out.println("=====================================");
}
当我运行应用程序时 - 我看到了
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'validatorHolder' defined in file [D:\freelance\demo\target\classes\com\example\domain\ValidatorHolder.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.domain.ValidatorHolder]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.example.domain.ValidatorHolder.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1044)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:759)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:689)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:969)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:958)
at com.example.DemoApplication.main(DemoApplication.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.domain.ValidatorHolder]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.example.domain.ValidatorHolder.<init>()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1092)
... 20 common frames omitted
Caused by: java.lang.NoSuchMethodException: com.example.domain.ValidatorHolder.<init>()
at java.lang.Class.getConstructor0(Class.java:3074)
at java.lang.Class.getDeclaredConstructor(Class.java:2170)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
... 21 common frames omitted
P.S.2问题与构造函数
上的错过@Autowired
有关
解决此问题后
System.out.println(validatorHolder1.getMyValidator() == validatorHolder2.getMyValidator());
返回true
但如果有点替换MyValidator代码:
@Service
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class MyValidator {
Object object = new Object();
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
System.out.println(validatorHolder1.getMyValidator() == validatorHolder2.getMyValidator());
真
System.out.println(validatorHolder1.getMyValidator().getObject() == validatorHolder2.getMyValidator().getObject());
假
甚至
System.out.println(validatorHolder1.getMyValidator().getObject() == validatorHolder1.getMyValidator().getObject());
假
答案 0 :(得分:3)
你误解了方法注入技术。你需要让你的bean抽象起来才能工作:
public class MyValidator {}
public abstract class ValidatorHolder {
public abstract MyValidator getMyValidator();
}
现在您可以按如下方式在XML中定义bean:
<bean class="com.somepackage.MyValidator" scope="prototype" />
<bean class="com.somepackage.ValidatorHolder">
<lookup-method name="getMyValidator" bean="myValidator" />
</bean>
在这种情况下,Spring将创建一个ValidatorHolder
的匿名子类,它返回每个类型调用的原型bean(一个新副本)。
使用带注释的服务类,无法进行查找方法注入,但这是您使用@Configuration
类执行此操作的方法:
@Configuration
public class MyConfiguration{
@Bean
@Scope("prototype")
public MyValidator myValidator(){
return new MyValidator();
}
@Bean
public ValidatorHolder validatorHolder(){
return new ValidatorHolder(){
@Override public MyValidator getMyValidator(){
return myValidator();
}
};
}
}
在这种情况下,您自己创建了ValidatorHolder
的子类,您可以清楚地看到发生了什么。
但是,只有使bean和提供者方法抽象化时,任一版本才有效。
最后,有三种不同的方法来定义spring bean:
@Service
,@Component
)
扫描@Configuration
使用@Bean
方法的课程。在您的示例代码中,您正在混合使用这三种样式,这几乎不是一个好主意。选择一种技术并坚持下去。
关于范围代理,这可以通过所有三种bean注册技术来实现。
a)XML
public class MyValidator {}
public class ValidatorHolder {
private MyValidator myValidator;
public void setMyValidator(MyValidator myValidator){
this.myValidator = myValidator;}
public MyValidator getMyValidator();
}
<bean class="com.somepackage.MyValidator" scope="prototype" />
<bean class="com.somepackage.ValidatorHolder">
<aop:scoped-proxy />
</bean>
b)带注释的服务类
@Service @Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class MyValidator {}
@Service
public class ValidatorHolder {
@Autowired
public ValidatorHolder(MyValidator myValidator){
this.myValidator=myValidator;
}
private final MyValidator myValidator;
public MyValidator getMyValidator(){ return myValidator; };
}
c)@Configuration
类,类似于XML版本的Bean类
@Configuration
public class MyConfiguration{
@Bean
@Scope("prototype")
public MyValidator myValidator(){
return new MyValidator();
}
@Bean
public ValidatorHolder validatorHolder(){
return new ValidatorHolder(myValidator());
}
}
请注意,所有代理解决方案将始终返回相同的对象,即代理。但底层功能将委托给不同的对象。通过将此代码添加到MyValidator来尝试:
private int counter = 1;
public int counter(){
return counter ++;
}
现在,与您调用此代码的频率无关:
validatorHolder.getMyValidator().counter();
它将始终返回1
。
答案 1 :(得分:0)
@Service
public class ValidatorHolder {
@Autowired
ApplicatioContext context;
public MyValidator getMyValidator() {
return context.getBean(MyValidator.class);
}
}