• spring bean的自动装配


    两种方式

    byName:自动查找容器上下文,set方法名 与 bean id 名相同

    byType: 自动查找容器上下文, class名称与类名相同

    案例

    人有猫和狗

    1、pojo

    cat.java

    package com.wt.pojo;
    
    public class Cat {
        public void shout(){
            System.out.println("mao~");
        }
    }

    mao.java

    package com.wt.pojo;
    
    public class Dog {
        public void shout(){
            System.out.println("wang~");
        }
    }

    person.java

    package com.wt.pojo;
    
    
    public class Person {
        private String name;
        private Dog dog;
        private Cat cat;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Dog getDog() {
            return dog;
        }
    
        public void setDog(Dog dog) {
            this.dog = dog;
        }
    
        public Cat getCat() {
            return cat;
        }
    
        public void setCat(Cat cat) {
            this.cat = cat;
        }
    }

    2、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
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="cat" class="com.wt.pojo.Cat"/>
    <bean id="dog" class="com.wt.pojo.Dog"/>
    <!--byName方法 自动在容器上下文中查找 set后面的名字 与 id 相同-->
    <bean id="per2" class="com.wt.pojo.Person" scope="singleton" autowire="byName" name="person2">
        <property name="name" value="tom"/>
    </bean>
        
    <!--byType方法 自动查询容器中 class名称与实现类 相同的类-->
        <bean id="person" class="com.wt.pojo.Person" scope="singleton" autowire="byType" name="per">
            <property name="name" value="tom"/>
        </bean>
    
    </beans>

    3、测试

    import com.wt.pojo.Person;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyTest {
    
        @Test
        public void getPerson(){
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            Person person = context.getBean("per", Person.class);
            System.out.println(person.getName());
            person.getCat().shout();
            person.getDog().shout();
        }
    }
  • 相关阅读:
    前端数组去重
    前端三栏布局
    JS运行三部曲(预编译)
    前端常用开发工具
    前端性能监控你会监控哪些数据? 如何做?
    H5与客户端交互的方式有哪些? 怎么做?
    http协议的状态码400,401,403,404,500,502,503,301,302等常见网页错误代码
    随笔记录
    Browser Events 常用浏览器事件
    MYSQL 索引的优点
  • 原文地址:https://www.cnblogs.com/wt7018/p/13337882.html
Copyright © 2020-2023  润新知