Spring-IOC简单实例

最近想自学Spring Boot,没成想不会Spring想自学SpringBoot太难了,于是就先学习了下Spring。下面是在学习Spring 中的IOC时写的简单的程序方便理解。

1 package ZS_ZDZP;
2 
3 public class Cat {
4     public Cat(){
5         System.out.println("miao!!!");
6     }
7 }
Cat
1 package ZS_ZDZP;
2 
3 public class Dog {
4     public Dog(){
5         System.out.println("wang!!!");
6     }
7 }
Dog
 1 package ZS_ZDZP;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Qualifier;
 5 
 6 public class People {
 7     @Autowired
 8     @Qualifier(value = "dog1")
 9     private Dog dog;
10     @Autowired
11     @Qualifier(value = "cat2")
12     private Cat cat;
13 
14     private String name;
15 
16     public Dog getDog() {
17         return dog;
18     }
19 
20     public void setDog(Dog dog) {
21         this.dog = dog;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         this.name = name;
30     }
31 
32     public Cat getCat() {
33         return cat;
34     }
35 
36     public void setCat(Cat cat) {
37         this.cat = cat;
38     }
39 
40     public People(Dog dog, Cat cat, String name) {
41         this.dog = dog;
42         this.cat = cat;
43         this.name = name;
44     }
45 
46     public People() {
47     }
48 
49     @Override
50     public String toString() {
51         return "ZDZP_People{" +
52                 "dog=" + dog +
53                 ", cat=" + cat +
54                 ", name='" + name + '\'' +
55                 '}';
56     }
57 
58 }
People
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6         https://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context
 8         https://www.springframework.org/schema/context/spring-context.xsd">
 9 
10 <!--    配置注解的支持-->
11     <context:annotation-config/>
12 
13     <bean id="cat1" class="ZS_ZDZP.Cat"></bean>
14     <bean id="cat2" class="ZS_ZDZP.Cat"></bean>
15     <bean id="dog1" class="ZS_ZDZP.Dog"></bean>
16     <bean id="dog2" class="ZS_ZDZP.Dog"></bean>
17     <bean id="peo" class="ZS_ZDZP.People" >
18         <property name="name" value="yang"></property>
19     </bean>
20 
21 </beans>
ZS_ZDZP_Bean.xml
1    public void test1(){
2         ApplicationContext context = new ClassPathXmlApplicationContext("ZS_ZDZP_beans.xml");
3         People p = context.getBean("peo",People.class);
4         String show =  p.toString();
5         System.out.println(show);
6     }
Test

 

posted @ 2021-04-27 15:02  doublebest1  阅读(133)  评论(0编辑  收藏  举报