无法在组件注释类内手动实例化类



我正在了解Spring,我偶然发现了这些奇特的东西。

我在下面有一个名为MyComponent的Component注释类(请忽略接口(,该类使用HelperClass。对于名为doSomething的方法中的两个不同变量,该助手类被手动实例化了两次

我还有我的豆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>

我的问题是:

  1. 我知道如果我在HelperClass上使用@autowired,它将具有来自bean的XML的属性值,但为什么即使我手动实例化这个类(HelperClass helper = new HelperClass()(,它仍然会发生
  2. 这背后的弹簧机制是什么
  3. 我可以禁用或阻止它在特定类中发生吗
  4. 即使我多次实例化它,为什么它们仍然指向或引用HelperClass的单个实例?听起来它的范围是辛格尔顿
  5. 如果我得到了前面问题的答案,我的下一个问题是如何在不引用bean的情况下完美地实例化HelperClass,我的意思是如何禁用这些事情发生在类中的特定行上

如果你觉得我的问题是多余的,请帮助我重定向

感谢

您很有可能被打印误导了。如果类在构造函数、字段或setter上有这样的注释,Spring可以自动连接依赖项。Spring不控制手动创建的实例。

Spring甚至无法进入您的方法,因为框架(在标准情况下(使用反射与类的接口进行操作。在启动时,框架会遍历所有类,找到所有必须处理的注释,并用代理覆盖这些类(几乎总是(。但是Spring从不直接进入代码内部,它不能在同一方法中的两行代码之间放入新的代码行。

最新更新