spring IOC demo

1、使用xml文件配置:

  创建applicationContext.xml,在该文件中创建需要的bean,

<bean id="hello" class="springdemo.HelloSpring"></bean>

此语句即可创建该类对象,即控制反转,使用容器创建对象。

  属性注入:分为set方法与构造方法注入,构造方法可使用下标索引或者数据类型进行对应注入,或者都使用。set注入则使用name=“属性名”进行注入。spring只检查是否有属性对象的set方法,不检查是否有该属性,如setName()方法。

1     <bean id="hello" class="springdemo.HelloSpring">
2         <constructor-arg index="0" value="kobe"></constructor-arg>
3         <constructor-arg index="1" value="44"></constructor-arg>
4         <property name="name" value="多帅哦"></property>
5         <property name="num" value="22"></property>
6     </bean>  

  p标签:简化配置信息

1 <bean id="hello" class="IOCdemo.HelloSpring"
2         p:name="帅的不谈"
3         p:num="22"
4     />

静态工厂注入:把静态方法放入bean中。

<bean id="carFactory" class="springdemo.CarFactory" factory-method="getCar"></bean>

2、使用注解:

  使用包扫描工具

<context:component-scan base-package="springAutoDemo"></context:component-scan>

  使用Component、Service、Repository、Controller注解把一个类标注为一个bean,使用Autowired注解实现bean的依赖注入

 1 package springAutoDemo;
 2 
 3 import org.springframework.stereotype.Component;
 4 
 5 @Component
 6 public class Person {
 7 
 8     private String name;
 9     private int age;
10     
11     public String getName() {
12         return name;
13     }
14     public void setName(String name) {
15         this.name = name;
16     }
17     public int getAge() {
18         return age;
19     }
20     public void setAge(int age) {
21         this.age = age;
22     }
23     
24     @Override
25     public String toString() {
26         return "User [name=" + name + ", age=" + age + "]";
27     }
28     
29 }
 1 package springAutoDemo;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Service;
 5 
 6 @Service
 7 public class Student {
 8 
 9     private Person person;
10     
11     @Autowired
12     public void setPerson(Person person) {
13         this.person = person;
14     }
15 
16 
17     public void getPerson() {
18         System.out.println(person.toString());
19     }
20     
21 }

测试类

 1 package springAutoDemo;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class AutoTest {
 7 
 8     public static void main(String[] args) {
 9         
10         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
11         
12         Student student = context.getBean("student", Student.class);
13         student.getPerson();
14         
15     }
16     
17 }
原文地址:https://www.cnblogs.com/lsy-lsy/p/10991708.html