1、传统的写配置文件的方式,配置一个类然后使用是用下面的方法:
使用:
2、使用注解的方式:
//告诉spring这是一个配置类
@Configuration
public class Anno {
//给容器中注册一个bean,类型为返回值类型 id是默认方法名作为id
@Bean
public Person person(){
return new Person("hdx",27);
}
}
使用:
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Anno.class);
Person bean = context.getBean(Person.class);
System.out.println(bean.name); //输出结果 hdx
//查看bean的名称
String[] beanNamesForType = context.getBeanNamesForType(Person.class);
for (String name : beanNamesForType) {
System.out.println(name); //输出结果 person
}
}
此时如果我想改变bean的名称当然可以直接改,但是也可以在注解里面指定
@Bean("person_alias")
public Person person(){
return new Person("hdx",27);
}
3、关于包扫描
之前的做法是配置component-scan,这时候只要指定路径底下的文件配置了 @service @controller @Repository @component注解的都会被扫描到
用注解的做法:可以指定排除哪些包或者只包含哪些
4、@scope设置组件的作用域,单实例、多实例
首先确认下spring ioc容器里面的实例对象是否是单实例的——yes
//spring IOC容器取出的对象都是单实例的
ApplicationContext context = new AnnotationConfigApplicationContext(Anno.class);
Object person = context.getBean("person_alias");
Object persons = context.getBean("person_alias");
System.out.println(person==persons); //true
添加scope注解可以控制bean的作用范围:
默认IOC容器启动都是创建单实例放到容器中,如果调成多实例
懒加载:
Conditional:按照一定的条件初始化bean
@import快速导入组件到IOC里
@Import(Color.class)