1、創(chuàng)建對象時,向類屬性里面設置值
2、java屬性注入的三種方式
-
set方法
image.png -
有參構造
image.png -
接口注入
image.png
3、在spring中只支持兩種方式
(1)set方法注入
PropertyUser.java
package work.zhangdoudou.Property;
public class PropertyUser {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- set方法注入屬性 -->
<bean id="propertyUser" class="work.zhangdoudou.Property.PropertyUser">
<!-- set方法注入屬性 -->
<property name="username" value="lisi"></property>
</bean>
</beans>
測試類TestPropertyUser.java
package work.zhangdoudou.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import work.zhangdoudou.Property.PropertyUser;
public class TestPropertyUser {
@Test
public void test() {
//1加載配置文件,根據(jù)創(chuàng)建對象
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//2得到創(chuàng)建的對象
PropertyUser propertyUser=(PropertyUser) context.getBean("propertyUser");
System.out.println(propertyUser.getUsername());
}
}
運行結果

image.png
(2)有參數(shù)構造注入
PropertyUser1.java
package work.zhangdoudou.Property;
public class PropertyUser1 {
private String username;
public PropertyUser1(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 有參數(shù)構造注入屬性 -->
<bean id="propertyUser1" class="work.zhangdoudou.Property.PropertyUser1">
<!-- 有參數(shù)構造注入 -->
<constructor-arg name="username" value="zhangsan"></constructor-arg>
</bean>
</beans>
測試類TestPropertyUser1.java
package work.zhangdoudou.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import work.zhangdoudou.Property.PropertyUser1;
public class TestPropertyUser1 {
@Test
public void test() {
//1加載配置文件,根據(jù)創(chuàng)建對象
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//2得到創(chuàng)建的對象
PropertyUser1 propertyUser1=(PropertyUser1) context.getBean("propertyUser1");
System.out.println(propertyUser1.getUsername());
}
}
運行結果

image.png


