spring可以使用xml和注解的方式注入beans。而注解有很多,下面会介绍一些有用的注解
@ComponentScan
如果全都使用注解,不参杂一点xml,可以建立一个配置类ApplicationConfig,然后使用@ComponentScan来配置扫描目录中含有注解的,然后将它注入到容器中。
但建议使用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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 设定Spring 去哪些包中找Annotation -->
<context:component-scan base-package="org.example"/>
</beans>
参考:1.10.3. Automatically detecting classes and registering bean definitions
@Component
将被注解的类加入到容器中
@Autowired
可以声明构造函数、属性、setter方法,声明后,容器根据参数类型将所需的对象将被注入进来。不能注解简单类型的属性
参考:Spring @Autowired Annotation
@Value
可以为简单类型的属性注入值。
@Primary
在使用@Autowired的时候,如果被注解的属性是一个接口,而接口的实现类有多个,那么容器就不知道该使用哪个实现类注入进来。那么使用@Primary在某个实现类上时,这个类会被优先使用被注入。
@Qualifier
上述问题也可以使用@Qualifier来解决,通过此注解指定具体的name属性值,将按名称的方式注入。
参考:Spring @Qualifier Annotation
@Resource
和@Autowired类似,不过是通过name名称来注入对象
@Required
被注释的方法必须要注入
参考:Spring @Required Annotation
@Configuration &@Bean
@Component只能注解在类上,而@Bean可以注解在方法上,该方法返回的bean将被装配到容器中。bean的name即为函数名,类型为放回值的类型。被注解的方法的类需要被@Configuration注解。
@Service & @Repository @Controller
与@Component并无什么区别,只是含有语义信息而已。
总的参考:
spring 学习之四(spring的注入方式(xml和annotation)
spring beans源码解读之--Bean的注解(annotation)
Java Web基础——Action+Service +Dao三层的功能划分