在spring中有三种装配的方式
-
在xml中显示的装配
-
在java中显示配置
-
隐式的自动装配bean【重要】
1.1、ByName,ByType自动装配
小结:
-
byname的时候,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性set方法值一致
-
bytype的时候,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
1.2 、使用注解实现自动装配要使用注解须知:
-
导入约束:context约束
-
配置注解的支持:context:annotation-config/
-
@Autowired:直接在属性上使用即可,如果自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=“xxx”)去配置@Autowired使用,指定一个唯一的bean对象注入。
小结:
@Resource和@Autowired的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过bytype的方式实现,再通过名字。@Qualifier(value=“xxx”)
- @Resource默认通过byname方式实现,如果找不到名字,则通过bytype实现。
-
bean
-
属性如何注入
-
衍生的注解
@Component有几个衍生注解,我们再web开发中,会按照mvc三层架构分层
-
dao 【@Repository】
-
service【@Service】
-
controller【@Controller】
代表将某个类注册到Spring中,装配bean
-
//这个也会被spring容器托管,注册到容器中,因为它本身就是一个@Component
//@Configuration代表这是一个配置类,等价于beans.xml
@Configuration
public class AppConfig {
//注册一个bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public MyService myService() {
return new MyServiceImpl();//就是返回注入到bean的对象
}
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}



