基于注解的方式配置Bean的属性

一:组件装配

1.context:component-scan 元素还会自动注册AutowiredAnnotationBeanPostProcessor实例,该实例可以自动装配具有@Autowired和@Resource,@Inject注解的属性

二:使用@Autowired自动装配Bean

1.@Autowired注解自动装配具有兼容类型的单个Bean属性

2.构造器,普通字段(即使是非public的),一切具有参数的方法都可以使用@Autowired注解

package com.dhx.annotation.controller;

import javax.annotation.Resource;

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

import com.dhx.annotation.service.UserService;

@Controller
public class UserController {
//	@Autowired   
	private UserService userService;
	
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public void execute() {
		System.out.println("UserController Execute ...");
		userService.add();
	}

}

3.默认情况下,所有使用@Autowired注解的属性都需要被设置,当spring找不到匹配的Bean装置属性时,会抛出异常。

若某一属性允许不被设置,可以设置@Autowired注解的required的属性为false

package com.dhx.annotation.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.stereotype.Repository;

import com.dhx.annotation.TestObject;

@Repository
public class UserRepositoryimpl implements UserRepository {
	@Autowired(required=false)
	private TestObject testObject;
	
	@Override
	public void save() {
		System.out.println("UserRepository Save ...");
		System.out.println(testObject);
	}

}

4.默认情况下,当IOC容器存在多个类型兼容的Bean时,通过类型装配的将无法工作,此时可以在@Qualifier注解里提供bean的名称,spring允许方法的入参标注@Qualifier已指定注入Bean的名称。

package com.dhx.annotation.service;

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

import com.dhx.annotation.repository.UserRepository;

@Service
public class UserService {
	
	/*@Autowired
	@Qualifier("userRepositoryimpl")*/
	private UserRepository userRepository;
	
	
	@Autowired
	public void setUserRepository(@Qualifier("userRepositoryimpl")UserRepository userRepository) {
		this.userRepository = userRepository;
	}
	
	public void add() {
		System.out.println("UserService add ...");
		userRepository.save();
	}

}

5.@Autowired注解也可以应用在数组类型属性上,此时spring将会把所有匹配到Bean进行自动装配

6.@Autowired注解也可以应用在集合属性上,此时spring读取该集合的类型信息,然后自动装配所有与之兼容的Bean

7.@Autowired注解用着java.util.Map上时,若该Map的键值为String,那么spring将自动装配与之Map值类型兼容的Bean,此时的Bean名称作为键值。

猜你喜欢

转载自blog.csdn.net/qq_39093474/article/details/85783994