gpt4 book ai didi

java - 使用 xml 配置不会禁用 Autowiring

转载 作者:行者123 更新时间:2023-12-02 12:06:48 25 4
gpt4 key购买 nike

尽管给 bean 的 autowire-candidate 属性设置了 false 值,它们还是会被 Autowiring 。无法找到我所缺少的东西。

Color.java

package org.manya.autowire;

public class Color {

private String color;

public void setColor(String color)
{
this.color = color;
}

public String getColor()
{
return this.color;
}

public String toString()
{
return this.color;
}
}

Engine.java

package org.manya.autowire;

public class Engine {
private String engine;

public void setEngine(String engine)
{
this.engine = engine;
}

public String getEngine()
{
return engine;
}

public String toString()
{
return this.engine;
}
}

Car.java

package org.manya.autowire;

public class Car {
private Color color;
private Engine engine;
public Color getColor() {
return color;
}
public void setColor(Color color) {
System.out.println("From the setter of Color in org.manya.innerBean.Car");
this.color = color;
}
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
System.out.println("From the setter of Engine in org.manya.innerBean.Car");
this.engine = engine;
}

public String toString()
{
return "This car has, engine : " + this.engine + ", color : " + this.color;
}
}

autowire.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean id="car" class="org.manya.autowire.Car" autowire="byName"
/>

<bean name="color" class="org.manya.autowire.Color" autowire-candidate="false">
<property name="color">
<value>Grey</value>
</property>
</bean>

<bean id="engine" class="org.manya.autowire.Engine" autowire-candidate="false"
p:engine="v10"
/>

</beans>

In autowire.xml i have declared car as autowired by name, but both of its dependencies i have declared as autowire-candidate as false. So this code should have given me an Exception. But when i am running it, Car is getting instantiated. What am i missing here?

最佳答案

根据这个Spring JIRA ticket autowire-candidate="false" 仅影响基于类型的 Autowiring 尝试,不会影响按名称的直接引用...也不会影响 autowire="byName"。

While the latter may be debatable, I'm not inclined to change it at this point since autowire="byName" is an outdated mechanism to begin with. I'm therefore turning this into a documentation issue.

关于java - 使用 xml 配置不会禁用 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com