Spring IOC @Autowired、@Qualifier 、@Primary 注解说明
#
1.@Autowired
依赖注入的注解
2.@Primary
官网文档的解释:
对应的翻译,来自搜狗(凑合可以看懂)
代码示例:
个人理解:在通过javaconfig进行声明bean时,加上该注解后,那个bean时首要选择。
3.@Qualifier
标识符,因为@Autowired默认时按照bean的类型注入(bytype),当别注入的接口有多个实现时,如果不加以区分,程序将会出现异常,使用@Qualifier进行标识来解决这个问题
示例:
声明的bean
package com.lhj.service;
public interface UserService {
void eat();
}
-------------------------------------------------------------
package com.lhj.service.impl;
import com.lhj.service.UserService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
public void eat() {
System.out.println("UserServiceImpl");
}
}
-------------------------------------------------------------
package com.lhj.service.impl;
import com.lhj.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceExtendImpl implements UserService {
public void eat() {
System.out.println("UserServiceExtendImpl");
}
}
注入并使用bean
package com.lhj.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class UserDemoService {
@Autowired
@Qualifier("userServiceExtendImpl")
private UserService userService;
}
添加@Qualifier来区分这里的UserServiceImpl 和UserServiceExtendImpl 两个bean ,@Qualifier括号内的值可以是bean的id或name值
官网文档说明:
搜狗翻译
还没有评论,来说两句吧...