自动装配

Posted xuweiweiwoaini

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自动装配相关的知识,希望对你有一定的参考价值。

1 概述

  • Spring利用依赖注入(DI),完成对IOC容器中各个组件的依赖关系的赋值。

 

2 @AutoWired注解&&@Qualifier注解&&@Primary注解

2.1 @AutoWired注解

  • 示例:
@Service
public class BookService {
    @Autowired
    private BookDao bookDao;

    public void print(){
        System.out.println(bookDao);
    }
}
  • 默认情况下,是按照类型去容器中寻找对应的组件。相当于
applicationContext.getBean(BookDao.class);
  • 如果有多个相同类型的组件,再将属性名作为组件的id去容器中寻找。相当于
applicationContext.getBean("bookDao");

 

  • 示例:
  • BookDao.java
package com.sunxiaping.dao;

import org.springframework.stereotype.Repository;

@Repository
public class BookDao {
}
  • BooService.java
package com.sunxiaping.serivice;

import com.sunxiaping.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookService {
    @Autowired
    private BookDao bookDao;

    public void print(){
        System.out.println(bookDao);
    }
}
  • BookController.java
package com.sunxiaping.controller;

import com.sunxiaping.serivice.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    public void print(){
        System.out.println(bookService);
    }
}
  • SpringConfig.java
package com.sunxiaping.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@ComponentScan(value = "com.sunxiaping")
@Configuration //告诉Spring这是一个配置类
public class SpringConfig {


}
  • 测试:
package com.sunxiaping.test;


import com.sunxiaping.config.SpringConfig;
import com.sunxiaping.controller.BookController;
import com.sunxiaping.serivice.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

        BookController bookController = context.getBean(BookController.class);

        bookController.print();

        BookService bookService = context.getBean(BookService.class);

        bookService.print();

    }

}

2.1 @Qualifier注解

 

以上是关于自动装配的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot学习探究Springboot自动装配

spring:按照Bean的名称自动装配User

Spring5 Java代码装配Bean

Spring装配bean--02通过Java代码装配bean

Sping实战之通过JAVA代码装配Bean

2018-03-30 装配bean之自动化装配