首先先说一下手动配置属性注入
当你有一个类时,有一些属性,并且有set/get方法时可以进行手动编写xml进行注入。
演示类如下:
public class Person {
private String name;
private Integer age;
private Date birthday;
public Integer getAge() {return age;}
public void setAge(Integer age) {this.age = age; }
public Date getBirthday() {return birthday; }
public void setBirthday(Date birthday) { this.birthday = birthday; }
public void setName(String name) {this.name = name; }
public String getName() { return name; }
}
手动进行注入如下:
<bean id="person" class="com.zjh.bean.Person">
<property name="name" value="张三"></property>
<property name="age" value="15"></property>
<property name="birthday" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean>
结果输入为:
Person{name='张三', age=15, birthday=Mon Jul 05 17:02:00 CST 2021}
当你使用注解进行注入的时候,并不需要该类必须有get/set方法
直接在属性上进行注入即可,上方的代码注入等效于下面的注解注入:
注解注入只需要xml文件中可以扫描到目标类,并且目标类上有注解@component即可
xml文件配置:
因为我的person类在com.zjh.bean包中,所以下面写的是com.zjh.bean
<context:component-scan base-package="com.zjh.bean">
</context:component-scan>
目标类:
@Component
public class Person {
@Value("张三")
private String name;
@Value("12")
private Integer age;
@Autowired
private Date birthday;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
}
运行结果:
Person{name=‘张三’, age=12, birthday=Mon Jul 05 17:06:28 CST 2021}
总结:
在注解中@Value等效于手动注入中的<property>
中的value
在注解中@Autowired等效于手动注入中的<property>
中的ref