使用注解定义Bean
@Component("user")
public class UserImpl implements User{}
@Component(“user”) 相当于
除了@Component()Spring还提供了三个特殊注解
- @Repository 用于标注Dao类
- @Service 用于标注业务类
- @Controller 用于标注控制器类
Spring提供了@Autowired注解实现Bean的装配
@Service("userService")
public class UserServiceImpl(){
@Autowired
private User u;
}
如果容器中有一个以上相同类型的Bean时 @Autowired就不可以用了 ,所以要用**@Qualifier(“user”)** 这里的user表示上面注解定义的bean
@Service("userService")
public class UserServiceImpl(){
@Qualifier("user")
private User u;
}
加载注解定义的Bean(ApplicationContext.xml文件中 两个注解间用逗号隔开)
<context:component-scan base-package="包名1,包名2"/>
使用java标准注解完成装配
为属性注入bean
@Resource(name=“bean的id”)
@Resource
不写后面括号就是匹配字段名或setter方法