spring的依赖注入是指在spring创建对象的过程中,将对象的依赖属性通过配置进行注入,我们先写个bean:
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
}
bean写好了,我们继续写配置文件:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--id是bean的唯一标识-->
<bean id="user" class="com.adwo.User">
<!--name是对象的属性名-->
<!--value是对该属性设置值-->
<property name="password" value="3344"></property>
</bean>
</beans>
下面写测试用例:
public static void main(String[] args) {
String path="beans.xml";
ApplicationContext app = new ClassPathXmlApplicationContext(path);
User user =(User) app.getBean("user");
user.setUsername("33");
System.out.println(user);
}
//打印
User [username=33, password=3344]
在这里我们可以看到打印的语句,既包含了我们手动设置的user.setUsername(“33”);也包含了在配置文件中的,也就是说配置文件中的property的作用就是user.setPassword(“3344”);