各位博友好,我看 spring 是可以配置默认装配方案的, 我配置了一个应用上下文中的 bean 的 autowire 属性为“byName”。按照预期它不是应该会自动将与属性名匹配的 Bean 装配到对应的Bean 属性中吗? 但我从运行结果来看 String、Integer 这两种类型没有被自动装配,而自定义类型StringPack 却能被自动装配,还望了解原因的博友指导下。
以下是我的代码清单:
public class StringPack {
private String value;
public StringPack(String value) {
this.value = value;
}
@Override
public String toString() {
return "StringPack{" +
"value='" + value + '\'' +
'}';
}
}
public class RemoteSkill {
private String skillName;
private Integer skillLevel;
private StringPack stringPack;
public void setSkillName(String skillName) {
this.skillName = skillName;
}
public void setSkillLevel(Integer skillLevel) {
this.skillLevel = skillLevel;
}
public void setStringPack(StringPack stringPack) {
this.stringPack = stringPack;
}
@Override
public String toString() {
return "RemoteSkill{" +
"skillName='" + skillName + '\'' +
", skillLevel=" + skillLevel +
", stringPack=" + stringPack +
'}';
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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 自动装配-->
<bean id="skillName" class="java.lang.String">
<constructor-arg value="火球"/>
</bean>
<bean id="skillLevel" class="java.lang.Integer">
<constructor-arg value="3"/>
</bean>
<bean id="stringPack" class="com.daxuan.autowiring.StringPack">
<constructor-arg value=" 一个自定义类"/>
</bean>
<!--自动装配 -->
<bean id="fireball" class="com.daxuan.autowiring.RemoteSkill" autowire="byName"/>
</beans>
测试类:
public class AutowiringTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/daxuan/autowiring/spring-autowire.xml");
String skillName = context.getBean("skillName", String.class);
Integer skillLevel = context.getBean("skillLevel", Integer.class);
StringPack stringPack = context.getBean("stringPack", StringPack.class);
RemoteSkill fireball = context.getBean("fireball", RemoteSkill.class);
// 打印: 火球 3 StringPack{value=' 一个自定义类'}
System.out.println(skillName + " " + skillLevel + " " + stringPack);
// 打印:RemoteSkill{skillName='null', skillLevel=null, stringPack=StringPack{value=' 一个自定义类'}}
System.out.println(fireball);
}
}
利用 @Value 注解可以来实现基本属性的注入。
<bean id="引用名" class="实现类的包类名"></bean>
<bean id="userService" class="cn.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>