【发布时间】:2022-01-25 11:57:01
【问题描述】:
我在理解 Spring 的过程中,偶然发现了这些奇特的东西。
我有一个名为 MyComponent 的 Component 注释类(请忽略接口),并且该类使用 HelperClass。这个帮助类在名为doSomething的方法中为两个不同的变量手动实例化了两次
我还有我的 bean project-properties.xml,它也在 app-config.xml 中导入
是的,出于某种原因,HelperClass 有一个 Bean,并且每次被 @autowired 时它也有一个 Initial 值,即使它是手动实例化的,并且该值来自 bean xml。
@Component
public MyCompontent implement MyInterface {
public doSomething() {
HelperClass helper1 = new HelperClass();
HelperClass helper2 = new HelperClass();
// print the value set by helper1 and its not null, the value is from bean xml
System.out.println(helper1.getVariable1);
helper1.setVariable1("Set Value for Helper1");
helper2.setVariable1("Set Value for Helper2");
// print the value set by helper1 but it display the value of the helper 2
System.out.println(helper1.getVariable1);
}
}
public HelperClass {
private String variable1;
private String variable2;
public void variable1(String variable1){
this.variable1 = variable1
}
public String getvariable1() {
return this.variable1;
}
public void variable2(String variable2){
this.variable2 = variable2
}
public String getvariable2() {
return this.variable2;
}
}
项目属性.xml
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myHelper" class="com.example.HelperClass">
<property name="variable1" value="bean-value1"/>
<property name="variable1" value="bean-value2"/>
</bean>
</beans>
app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
...........
<!-- Configures Spring MVC -->
<import resource="project-properties.xml"/>
.....
.....
</beans>
我的问题是:
- 我知道如果我在 HelperClass 上使用 @autowired 它将具有来自 bean 的 XML 的属性值,但为什么即使我手动实例化此类 (
HelperClass helper = new HelperClass()) 仍然会发生? - 这背后的弹簧机制是什么?
- 我可以禁用此功能或阻止它在特定课程中发生吗?
- 即使我多次实例化它,为什么它们仍然指向或引用 HelperClass 的单个实例?听起来它的作用域是 Singleton。
- 如果我得到了前面问题的答案,我的下一个问题是如何在不参考 bean 的情况下完美地实例化 HelperClass,我的意思是如何禁止这些事情发生在类中的特定行上?
如果您觉得我的问题是多余的,请帮我重定向
感谢和问候
【问题讨论】:
-
它没有。所以实际上你描述的没有意义。除非您使用
@Configurable和适当的 AspectJ 代理来运行您的应用程序,否则我对此表示怀疑。所以我怀疑你在这里显示的代码是你实际使用的代码。我怀疑您在此处显示的代码中缺少一些static关键字。 -
我太笨了,我没看到那个静态的,谢谢!!我昨天注意到了代码对不起:D
标签: spring spring-boot spring-mvc