Spring自动装配之方法、构造器位置的自动注入

  • Post author:
  • Post category:其他



目录


1. 注解定义


2. 注解使用


3. 注入位置推荐


1. 注解定义

@Autowired的定义信息如下:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

	/**
	 * Declares whether the annotated dependency is required.
	 * <p>Defaults to {@code true}.
	 */
	boolean required() default true;

}

可以看出,@Autowired注解可以定义在构造器上,方法上,方法参数上,字段上,还有自定义注解上;

2. 注解使用

  • 2.1 定义在造器上
@Autowired //定义在构造器方法上
public UserService(UserDao userDao) {
	this.userDao = userDao;
}

或者

// 定义在构造器参数上
public UserService(@Autowired UserDao userDao) {
	this.userDao = userDao;
}


特别注意,当一个类只有一个有参构造器,且该构造器不一定需要是public修饰的, 组件注入的时候不需要指定在构造器方法上或者构造器参数上指定@Autowired,只需要声明构造器即可;

  • 2.2 定义在方法和参数上

定义在Set方法上

@Autowired //定义在set方法上
public void setUserDao(UserDao userDao) {
	this.userDao = userDao;
}

定义在配置Bean的方法上

package com.yibai.spring.annotation.main.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import com.yibai.spring.annotation.service.UserDao;
import com.yibai.spring.annotation.service.UserService;

//@ComponentScan("com.yibai.spring.annotation.service")
@Service
public class MainConfigForAutowired {

	// Spring自动从IOC容器中找出UserDao作为方法参数传入,这里@Autowired可有可无
	@Bean
	public UserService userService(@Autowired UserDao userDao) {
		UserService userService = new UserService();
		userService.setUserDao(userDao);
		return userService;
	}

	@Bean
	public UserDao userDao() {
		return new UserDao();
	}
}
  • 2.3 定义在字段上
package com.yibai.spring.annotation.service;

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

import lombok.Getter;

@Getter
@Service
public class UserService {

	@Qualifier(value = "userDao")
	@Autowired(required = true)
	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}

3. 注入位置推荐

一般推荐注入位置放在构造器上,因为不管字段还是方法的方式注入,都是先创建组件,再注入依赖的组件,如果在构造方法上就需要使用依赖的组件,那么只有在构造器上注入才是可以实现的,因为执行顺序的问题;

package com.yibai.spring.annotation.service;

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

import lombok.Getter;

@Getter
@Service
public class UserService {

	@Qualifier(value = "userDao")
	@Autowired(required = true)
	private UserDao userDao;

	public UserService() {
		//@Autowired定义在字段或者set方式上,在构造器上无法获取到依赖的组件
		System.out.println(userDao); // null
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}



版权声明:本文为luojinbai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。