Spring三种方法的注解自动注入

1 @Autowired注解

@Autowired是Spring提供的自动注入的方法,该注解可以放在变量和方法上,在bean+返回值类型的注解中,@Autowired还可以放在参数前;@Autowired默认的注入是根据类型注入,如果相同类型的bean有多个,可以配合@Qualifier使用,则会根据名字自动注入;除了配合@Qualifier使用之外,还可以在相同类型的多个bean中的其中一个加上@Primary注解,那么根据类型注入就会第一注入有@Primary注解的bean。

示例代码:

@Repository("stuDao1")
public class StudentDaoImpl1 implements StudentDao {
}
@Primary
@Repository("stuDao2")
public class StudentDaoImpl2 implements StudentDao {
}
@Service("stuService")
public class StudentService {
	
	@Autowired	//从IOC容器中找到StudentDao类型的bean加入到studentDao中,AutoWired注入不调用set方法
	@Qualifier("stuDao")
	private StudentDao studentDao;

	//@Autowired	//也可以把AutoWired注解放到set方法上,并且会调用set方法
	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}
}

2 @Resource

@Resource注解是Java规范(JSR250)提供的方法,该注解默认是根据bean的名字自动注入,如果没有找到对应的名字,则会自动根据类型查找并注入,可以使用name和type来指定根据名字还是类型来查找;@Resource注解同样可以使用@Primary。

示例代码:

public class StudentService {

//	@Resource(name="stuDao1") //根据名字查找bean
	@Resource(type=StudentDao.class)    //根据类型查找bean
	private StudentDao studentDao;

//  @Resource    //放在方法上
	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}
}

3 @Inject

@Inject注解也是Java规范(JSR330)提供的方法,该注解默认是根据bean的类型自动注入,不过使用此注解需要导入javax-Inject.jar包;使用方法和@Autowired差不多一样,也可以配合@Qualifier和@Primary使用。

javax-Inject.jar下载地址

示例代码

@Service("stuService")
public class StudentService {

//	@Inject
//	@Qualifier("stuDao2")
	private StudentDao studentDao;

	@Inject
	@Qualifier("stuDao2")
	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

}
 
发布了63 篇原创文章 · 获赞 28 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41286145/article/details/102585097