Spring学习十----------Bean的配置之Autowired注解实现

© 版权声明:本文为博主原创文章,转载请注明出处

@Required

[email protected]注解适用于bean属性的setter方法

-这个注解仅仅表示,受影响的bean属性必须在配置时被填充,通过在bean定义或通过自动装配一个明确的属性值

@Autowired

-可以将@Autowired注解为“传统”的setter方法

-可用于构造器或成员变量

-默认情况下,如果因找不到合适的bean将会导致autowiring失败跑出异常,可通过@Autowired(required=false)避免

-每个类只能有一个构造器被标记为required=true

[email protected]的必要属性,建议使用@Required注解

-可以通过添加注解给需要该类型的数组的字段或方法,以提供ApplicationContext中所有特定类型的bean

-可以用于装配key为String的Map

-如果希望数组有序,可以让bean实现org.springframework.core.Ordered接口或使用@Order注解

[email protected]是由Spring BeanPostProcessor处理的,所以不能再自己的BeanPostProcessor或BeanFactoryPostProcessor类型应用这些注解,这些类型必须通过XML或者Spring的  @Bean注解加载

@Qualifier

-按类型自动装配可能多个bean实例的情况,可以使用使用Spring的@Qualifier注解缩小范围(或指定唯一),也可以用于指定单独的构造器参数或方法参数

-可用于注解集合类型变量

@Resource

-通过其独特的名称来定义识别特定的目标(这是一个与所声明的类型无关的匹配过程)

-因语义差异,集合和Map类型的bean无法通过@Autowired来注入,因为没有类型匹配到这样的bean,为这些bean使用@Resource注解,通过唯一名称引用集合或Map的bean

实例:

1.项目结构

2.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
  
	<groupId>org.springautowired</groupId>
	<artifactId>Spring-Autowired</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Spring-Autowired Maven Webapp</name>
	<url>http://maven.apache.org</url>
	
	<properties>
		<spring.version>4.3.8.RELEASE</spring.version>
	</properties>
	
	<dependencies>
		<!-- junit依赖 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<!-- spring核心依赖 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-core</artifactId>
		    <version>${spring.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-beans</artifactId>
		    <version>${spring.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context</artifactId>
		    <version>${spring.version}</version>
		</dependency>
	</dependencies>
	
	<build>
		<finalName>Spring-Autowired</finalName>
	</build>
	
</project>

3.spring-autowired.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
    <!-- 开启包扫描将Bean加载到IOC容器中 -->
  <context:component-scan base-package="org.springautowired.*"/>        
        
</beans>

 4.BeanDao.java

package org.springautowired.dao;

public interface BeanDao {

	public void save(String key);
	
}

5.BeanDaoImpl.java

package org.springautowired.dao.impl;

import org.springautowired.dao.BeanDao;
import org.springframework.stereotype.Repository;

@Repository
public class BeanDaoImpl implements BeanDao {

	public void save(String key) {
		
		System.out.println("BeanDaoImpl保存成功,保存的数据为:" + key);
		
	}

}

6.BeanService.java

package org.springautowired.service;

public interface BeanService {

	public void save(String key);
	
}

7.BeanServiceImpl.java

  7.1 注解在成员变量上

package org.springautowired.service.impl;

import org.springautowired.dao.BeanDao;
import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BeanServiceImpl implements BeanService {

	@Autowired
	private BeanDao beanDao;
	
	public void save(String key) {
		
		System.out.println("BeanServiceImpl接受参数:" + key);
		beanDao.save(key);
		
	}
	
}

  7.2 注解在构造器上

package org.springautowired.service.impl;

import org.springautowired.dao.BeanDao;
import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BeanServiceImpl implements BeanService {

	private BeanDao beanDao;

	@Autowired
	public BeanServiceImpl(BeanDao beanDao) {
		this.beanDao = beanDao;
	}

	public void save(String key) {
		
		System.out.println("BeanServiceImpl接受参数:" + key);
		beanDao.save(key);
		
	}
	
}

  7.3 注解在setter方法上

package org.springautowired.service.impl;

import org.springautowired.dao.BeanDao;
import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BeanServiceImpl implements BeanService {

	private BeanDao beanDao;
	
	@Autowired
	public void setBeanDao(BeanDao beanDao) {
	    this.beanDao = beanDao;
	}

	public void save(String key) {
		
		System.out.println("BeanServiceImpl接受参数:" + key);
		beanDao.save(key);
		
	}
	
}

8.BeanController.java

  8.1 注解在成员变量上

package org.springautowired.controller;

import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class BeanController {
	
	@Autowired
	private BeanService beanService;

	public void save(String key) {
		
		System.out.println("BeanController开始执行插入方法");
		beanService.save(key);
		
	}
	
}

  8.2 注解在构造器上

package org.springautowired.controller;

import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class BeanController {
	
	private BeanService beanService;
	
	@Autowired
	public BeanController(BeanService beanService) {
		this.beanService = beanService;
	}

	public void save(String key) {
		
		System.out.println("BeanController开始执行插入方法");
		beanService.save(key);
		
	}
	
}

  8.3 注解在setter方法上

package org.springautowired.controller;

import org.springautowired.service.BeanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class BeanController {
	
	private BeanService beanService;
	
	@Autowired
	public void setBeanService(BeanService beanService) {
		this.beanService = beanService;
	}

	public void save(String key) {
		
		System.out.println("BeanController开始执行插入方法");
		beanService.save(key);
		
	}
	
}

9.BeanInterface.java

package org.springautowired.mutil;

public interface BeanInterface {

}

10.BeanInterfaceImpl1.java

package org.springautowired.mutil;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(2)
@Component
public class BeanInterfaceImpl1 implements BeanInterface {

}

11.BeanInterfaceImpl2.java

package org.springautowired.mutil;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(1)
@Component
public class BeanInterfaceImpl2 implements BeanInterface {

}

12.MultiBean.java

package org.springautowired.mutil;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class MultiBean {

	//使用@Autowired将所有实现BeanInterface接口的类放入list中,可用@Order指定顺序
	@Autowired
	private List<BeanInterface> list;
	
	//使用@Autowired将所有实现BeanInterface接口的类放入map中,bean ID作为key
	@Autowired
	private Map<String, BeanInterface> map;
	
	//使用@Qualifier缩小范围(指定唯一)
	@Autowired
	@Qualifier("beanInterfaceImpl2")
	private BeanInterface beanInterface;
	
	//@Resource通过名字注入,与上一样
	@Resource
	private BeanInterface beanInterfaceImpl2;
	
	public void say() {
		
		if(list != null && list.size() > 0) {
			System.out.println("list...");
			for(BeanInterface bean: list) {
				System.out.println(bean.getClass().getName());
			}
		}else{
			System.out.println("List<BeanInterface> is null");
		}
		
		if(map != null && map.size() > 0) {
			System.out.println("map...");
			for(String key: map.keySet()){
				System.out.println(key + "   " + map.get(key).getClass().getName());
			}
		}else{
			System.out.println("Map<String, BeanInterface> is null");
		}
		
		System.out.println("@Qualifier...");
		if(beanInterface != null){
			System.out.println(beanInterface.getClass().getName());
		}else{
			System.out.println("beanInterface is null");
		}
		
		System.out.println("@Resource...");
		if(beanInterfaceImpl2 != null){
			System.out.println(beanInterfaceImpl2.getClass().getName());
		}else{
			System.out.println("beanInterfaceImpl2 is null");
		}
		
	}
	
}

13.TestBase.java

package org.springautowired.test;

import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

public class TestBase {

	private ClassPathXmlApplicationContext context;
	private String springXmlPath;
	
	/**
	 * 无参构造器
	 */
	public TestBase() {

	}
	
	/**
	 * 含参构造器,初始化spring配置文件路径
	 * 
	 * @param springXmlPath
	 * 						spring配置文件路径
	 */
	public TestBase(String springXmlPath) {

		this.springXmlPath = springXmlPath;
		
	}
	
	/**
	 * 初始化spring配置文件到IOC容器中
	 */
	@Before
	public void before() {
		
		if(StringUtils.isEmpty(springXmlPath)){//默认spring配置文件路径
			springXmlPath = "classpath:spring-*.xml";
		}
		context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]+"));
		context.start();
		
	}
	
	/**
	 * 销毁IOC容器
	 */
	@After
	public void after() {
		
		if(context != null) {
			context.destroy();
		}
		
	}
	
	/**
	 * 通过bean ID获取bean对象
	 * 
	 * @param beanId
	 * 					bean ID
	 * @return
	 */
	public Object getBean(String beanId) {
		
		return context.getBean(beanId);
		
	}
	
}

14.TestSpringAutowired.java

package org.springautowired.test;

import org.junit.Test;
import org.springautowired.controller.BeanController;
import org.springautowired.mutil.MultiBean;

public class TestSpringAutowired extends TestBase {

	/**
	 * 构造函数初始化spring配置文件
	 */
	public TestSpringAutowired() {
		
		super("classpath:spring-autowired.xml");
		
	}

	/**
	 * 测试@autowired在成员变量、构造器和setter方法上
	 */
	@Test
	public void testAutoWired() {
		
		BeanController beanController = (BeanController) super.getBean("beanController");
		beanController.save("test");
		
	}
	
	/**
	 * 测试@Autowired装配指定类型的数组和key为String的Map
	 */
	@Test
	public void testAutoWired2() {
		
		MultiBean bean = (MultiBean) super.getBean("multiBean");
		bean.say();
		
	}
	
}

15.效果预览

参考:http://www.imooc.com/video/4031

   http://www.imooc.com/video/4032

   http://www.imooc.com/video/4160

版权声明:本文为weixin_30436101原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30436101/article/details/96992024