Spring 学习——Spring注解——Autowiring(自动装配)

装配方式

  • 方式一:默认
  • 方式二:byName:根据属性名称自动装配。会查找Bean容器内部所有初始化的与属性名成相同的Bean,自动装配。(需要通过set方法注入,注入Bean的id名称需要和实体类的属性名称一致)
    复制代码
    <?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
            http://www.springframework.org/schema/beans/spring-beans.xsd"
        default-autowire="byName">
    
        <bean id="autoService" class="com.jing.spring.autowiring.AutoWiringService"></bean>
        <bean id="autoWiringDao" class="com.jing.spring.autowiring.AutoWiringDao"></bean> 
     </beans>
    复制代码
    复制代码
    ackage com.jing.spring.autowiring;
    
    public class AutoWiringService {
    
        private AutoWiringDao autoWiringDao;
    
        public void setAutoWiringDao(AutoWiringDao autoWiringTestDao) {
            this.autoWiringDao = autoWiringTestDao;
        }
    
        public void autoService(String arg){
            System.out.println("AutoWiringService.autoService===="+arg);
            autoWiringDao.autoDao(arg);
        }
    }
    复制代码
  • 方式三:byType:根据类型自动装配。如果容器中存在一个与所需Bean类型相同的Bean,则自动装配。如果存在多个相同类型的Bean,报错。找不到相匹配的Bean,什么都不发生。(需要通过set方法注入!!!)
    复制代码
    <?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
            http://www.springframework.org/schema/beans/spring-beans.xsd"
        default-autowire="byType">
    
        <bean class="com.jing.spring.autowiring.AutoWiringService"></bean>
        <bean class="com.jing.spring.autowiring.AutoWiringDao"></bean> 
     </beans>
    复制代码
  • Constructor:同byType相似。如果找不到匹配的Bean,报错。(需要通过构造方法注入,注入的Bean的id名称需要和实体类的属性名称一致!!!)
    复制代码
    <?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
            http://www.springframework.org/schema/beans/spring-beans.xsd"
        default-autowire="constructor">
    <bean id="autoService" class="com.jing.spring.autowiring.AutoWiringService"></bean> <bean id="autoWiringDao" class="com.jing.spring.autowiring.AutoWiringDao"></bean> </beans>
    复制代码
    复制代码
    package com.jing.spring.autowiring;
    
    public class AutoWiringService {
    
        private AutoWiringDao autoWiringDao;
    
        public AutoWiringService(AutoWiringDao autoWiringTestDao){
            this.autoWiringDao = autoWiringTestDao;
        }public void autoService(String arg){
            System.out.println("AutoWiringService.autoService===="+arg);
    
            autoWiringDao.autoDao(arg);
        }
    }
    复制代码

     

posted @ 2019-02-25 16:41  话·醉月  阅读(979)  评论(0编辑  收藏  举报