1. The first injection method: injection with a parameter constructor
Example:
User:
public class User {
private String name;
private String sex;
public User()
{
System.out.println("I'm a no-argument constructor for User.");
}
public User(String name,String sex)
{
this.name=name;
this.sex=sex;
System.out.println("I'm a two-parameter constructor for User.");
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\' ' +
", sex='" + sex + '\' ' +
'} ';
}
}
bean1.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.xsd">
<bean id="user" class="com.zcy.www.entity.User" >
<constructor-arg name="sex" value="Male"></constructor-arg>
<constructor-arg name="name" value="Late Breeze"></constructor-arg>
</bean>
</beans>Test: @ Test publicvoid test()
{
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean1.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
}
Copy the code
2. The second injection mode is SET injection
Example:
Bean. 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.xsd">
<bean id="user" class="com.zcy.www.entity.User" >
<property name="name" value="Late Breeze"></property>
<property name="sex>" value="Male"></property>
</bean>
</beans>
User:
public class User {
private String name;
private String sex;
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\' ' +
", sex='" + sex + '\' ' +
'} '; }}Copy the code
3. The third type of injection: P namespace injection (simplified SET injection)
Example:
bean.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="user" class="com.zcy.www.entity.User" p:name="Late Breeze" p:sex="Male">
</bean>
</beans>
Copy the code