Spring中四种依赖注入的方式(推荐注解注入)
注解注入(1)
注解注入 (2)
构造函数注入
代码如下(如果不会使用lombok插件的可以直接生成get、set、构造以及toString方法):
实体类 User.java
@Data
public class User {
private String username;
private String height;
public User(String username, String height) {
this.username = username;
this.height = height;
}
}
测试类UserTest.java
public class UserTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
User user = (User) context.getBean("user",User.class);
System.out.println(user);
}
}
配置文件 spring-context.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.zh.spring.test.entity.User">
<constructor-arg name="username" value="刘强西"></constructor-arg>
<constructor-arg name="height" value="175"></constructor-arg>
</bean>
</beans>