Spring Bean的三种注入方式
- setter 方法(属性)注入
- 构造方法注入
- 注解注入(@Resource和@Autowired,自动装配)
@Autowired 和 @Resource
@Autowired,Spring提供的注解,byType注入,默认情况下要求依赖必须存在;配置required=false表示依赖可为null
如果我们想使用@Autowired按照名称byName来装配,可以结合@Qualifier注解一起使用。
org.springframework.beans.factory.annotation.Autowired
@Resource默认按照ByName自动注入,由J2EE提供,需要导入包javax.annotation.Resource。
如果使用了@Resource注解,且没有配置name 和 type,默认使用byName装配,装配失败时,使用byType。 但如果你指定了name 或 type,则不会按上述逻辑装配
@Component:可以用于注册所有bean
@Repository:主要用于注册dao层的bean
@Controller:主要用于注册控制层的bean
@Service:主要用于注册服务层的bean