Spring依赖注入

  IoC(Inversion of Control),即控制反转。它使程序组件或类之间尽量形成一种轻耦合的结构,开发者在使用类的实例之前,需要先创建对象但是IoC将创建实例的任务交给IoC容器,这样开发应用代码时要直接使用类的实例,这就是IoC。相对于IoC,更为准确的概念是依赖注入。

  注入方式有3种:接口注入、Setter注入、构造器注入,Spring支持后俩种。

    接口注入:基于接口将调用与实现分离。这种依赖注入方式必须实现容器所规定的接口,是程序代码和容器的API绑定在一起,这不是理想的依赖注入方式。

    Setter注入:java代码

   
 1  public class User {
 2     private String name;
 3     private String sex;
 4     private int age ;
 5     public String getName() {
 6          return name ;
 7     }
 8     public void setName(String name) {
 9          this.name = name;
10     }
11     public String getSex() {
12          return sex ;
13     }
14     public void setSex(String sex) {
15          this.sex = sex;
16     }
17     public int getAge() {
18          return age ;
19     }
20     public void setAge(int age) {
21          this.age = age;
22     }
applicationContext.xml文件:
      
 1   <bean name= "user" class ="edu.sdut.text.User">
 2                <property name= "name">
 3                       <value> 小青</value >
 4                </property>
 5                <property name= "sex">
 6                       <value> 男</ value>
 7                </property>
 8                <property name= "age">
 9                       <value> 19</ value>
10                </property>
11         </bean>
主函数:
 1 public static void main(String[] args) {
 2          // 装载配置文件
 3         Resource resource = new ClassPathResource("applicationContext.xml" );
 4         BeanFactory factory = new XmlBeanFactory(resource);
 5          //获取bean
 6         User user = (User) factory.getBean("user" );
 7          //输出用户信息
 8         System. out.println("用户名:" + user.getName());
 9         System. out.println("年龄:" + user.getAge());
10         System. out.println("性别:" + user.getSex());
11     }
构造器注入:java代码
  
1 public User(String name,int age,String sex){
2 this.name = name;
3 this.age = age;
4 this.sex = sex;
5 }

  applicationContext.xml文件:

 1 <bean name="user" class="edu.sdut.text.User">
 2 <constructor-arg>
 3 <value>小柒</value>
 4 </constructor-arg>
 5 <constructor-arg>
 6 <value>18</value>
 7 </constructor-arg>
 8 <constructor-arg>
 9 <value>男</value>
10 </constructor-arg>
11 </bean>
原文地址:https://www.cnblogs.com/xiaochaozi/p/3365034.html