spring IOC demo

一、使用xml文件配置:spring

  建立applicationContext.xml,在該文件中建立須要的bean,app

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

此語句便可建立該類對象,即控制反轉,使用容器建立對象。ide

  屬性注入:分爲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中。this

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

二、使用註解:spa

  使用包掃描工具code

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

  使用Component、Service、Repository、Controller註解把一個類標註爲一個bean,使用Autowired註解實現bean的依賴注入component

 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 }

測試類xml

 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 }
相關文章
相關標籤/搜索