Spring
提供了几个注解来标注Spring bean
1.
@Component
: 标注一个普通的Spring Bean
2.@Controller
: 标注一个控制器组件类
3.@Service
: 标注一个业务逻辑组件类
4.@Repository
: 标注一个DAO
组件类还需要让
Spring
搜索指定包,将指定路径下的带有上述注解修饰的Java
类作为Bean
。@Scope
指定Bean
的作用域,如@Scope("prototype")
、@Scope("singleton")
@Resource(name = "xxx")
将容器中名为xxx
的对象注入PostConstruct
修饰的方法会和init-method
指定的方法一样,会在该Bean
注入后被调用。@PreDestory
修饰的方法和destory-method
指定的方法一样,会在Bean
销毁前调用。@DependsOn
强制初始化其他的Bean
如@DependsOn({"x1", "x2"})
当前Bean
被初始化之前,会强制初始化x1
、x2
两个Bean
@Lazy(true)
被修饰的类不会被预初始化Autowired
指定自动装配
1. 修饰方法
@Autowired
public void setAxe(Axe axe) {}
Spring
容器自动搜索类型为Axe
的Bean
实例注入到axe
中,如果有多个Axe
类型的Bean
,抛出异常。
2.修饰变量和修饰方法类似
3.修饰变量数组
@Autowired
private Axe[] axes;
修饰的变量为数组,则Spring
会搜索容器中所有Axe
类型的Bean
,将这些Bean
作为数组注入到axes
中。
@Qualifier
根据Bean
的id
自动装配
@Autowired
@Qualifier("axe")
private Axe axe;
将容器中id
为axe
的Bean
注入到axe
中。
这样的注入相当于@Resource(name = "axe")