开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第21天,点击查看活动详情
注解驱动
在xml驱动的IOC容器中,使用ClassPathXmlApplicationContext加载xml配置文件。对于注解配置的驱动,是使用AnnotationConfigApplicationContext来加载配置类的。
配置类:在类上标注@Configuration注解以使其变成配置类。如:
@Configuration
public class QuickstartConfiguration {
}
在注解驱动中可以使用@Bean注解,它等价于xml配置中的bean标签。当然还有一种方式可以把类放入IOC容器:通过@Component,这个注解是放在类上,将一个类变成bean对象,通过组件扫描的方式将bean注册到IOC容器。
组件扫描有两种形式,第一种是使用@ComponentScan注解,它会扫描指定包下的所有@Component组件。第二种方式是 new AnnotationConfigApplicationContext("com.linkedbear.spring.annotation.c_scan.bean");(不推荐)。
xml里面也是可以启用组件扫描的,用的是
<context:component-scan base-package="com.linkedbear.spring.annotation.c_scan.bean"/>
这里就不详细讲解了。
最后需要提一下的是@Bean和@Component两个注解之间的区别。
- @Bean只能一个一个的去注册组件,没有组件扫描,@Bean可以标注在方法上,支持第三方组件bean的引入。
- @Component可以组件扫描,标注在类上,不能标注在方法上,这就意味着它对第三方的组件bean就束手无策了。
注解驱动与xml互通 这里要说的是一个应用中既有注解配置,又有xml配置,这个时候需要由一方去引入另一方。 xml开启注解配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解配置 -->
<context:annotation-config />
<bean class="com.linkedbear.spring.annotation.d_importxml.config.AnnotationConfigConfiguration"/>
</beans>
注解引入xml配置,在配置类上使用@ImportResource注解,参数就是xml的类路径。如@ImportResource("classpath:annotation/beans.xml")。
依赖注入
这里想提的两个比较重要的:@Value和@Autowired。
- @Value主要用于注入一些属性,如:
@Value("black-value-anno")
private String name;
@Autowired是自动注入,可以给一个bean注入其他的bean。如
@Autowired
private Person person;
@Bean
@Autowired // 高版本可不标注
public Cat cat(Person person) {
Cat cat = new Cat();
cat.setName("mimi");
cat.setPerson(person);
return cat;
}
还可以加入@Qualifier指定注入的Bean的名称来显示注入,这样可以避免同一个类型的bean多个不同的的id导致spring不知道注入哪一个的情况。
另外还有一个注解要提:@Resource相当于@Autowired和@Qualifier。