一.Spring三种依赖注入的方式
-
Setter注入
-
注解方式
@Controller public class TestController { private TestService testService; @Autowired public void setTestService(TestService testService) { this.testService = testService; } }
-
XML方式
<bean id="testController" class="com.example.TestController"> <property name="testService" ref="testService" /> </bean>
-
-
构造器注入
-
注解方式
@Controller public class TestController { private TestService testService; //@Autowired声明在参数前面也支持 @Autowired public TestController(TestService testService) { this.testService = testService; } }
-
注解方式
<bean id="testController" class="com.example.TestController"> <constructor-arg ref="testService" /> </bean>
-
-
属性注入
-
注解方式
@Controller public class TestController { @Autowired private TestService testService; }
-
XML方式
<bean id="testController" class="com.example.TestController" autowire="byType" /> <bean id="testService" class="com.example.TestService" />
-
二.@Autowired和@Resource注解的区别
-
@Autowired是Spring提供的,@Resource是JDK提供的(和Spring解耦)
-
@Autowired先根据类型(byType)查找,如果存在多个 Bean 再根据名称(byName)查找
@Resource先根据名称(byName)查找,如果查不到,再根据类型(byType)进行查找
-
@Autowired支持Setter注入、构造器注入,属性注入,@Resource只支持Setter注入和属性注入
-
@Autowired和@Resource都默认强制注入,@Autowired可以通过设置required = false关闭
三.如果有多个Bean候选的情况下,@Autowired如何指定要注册的Bean
场景:@Autowired先根据类型(byType)查找,如果存在多个 Bean 再根据名称(byName)查找,如果查找不到,启动就会报错
@RestController
public class TestController {
//无法命中name为testService的bean,启动报错
@Autowired
private TestService testService;
@RequestMapping("run")
public void run() {
testService.run();
}
}
//beanName默认为首字母小写的驼峰:testServiceImpl1
@Service
public class TestServiceImpl1 implements TestService {
@Override
public void run() {
System.out.println("1");
}
}
//beanName为指定的serviceImpl2
@Service("serviceImpl2")
public class TestServiceImpl2 implements TestService {
@Override
public void run() {
System.out.println("2");
}
}
-
@Primary注解:Spring会优先注册声明了@Primary注解的Bean
@Service @Primary public class TestServiceImpl1 implements TestService { @Override public void run() { System.out.println("1"); } }
-
@Qualifier注解:通过value属性指定要注册的beanName
@RestController public class TestController { @Autowired @Qualifier(value = "serviceImpl2") private TestService testService; @RequestMapping("run") public void run() { testService.run(); } }