<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.3.12.RELEASEversion>
dependency>
spring-context jar包是Spring核心环境依赖包。
/**
* @Configuration注解告诉Spring这是一个配置类,类似Spring中的xml文件
*/
@Configuration
public class AnnotationConfig {
@Bean
public Person person() {
return new Person("xiaomin", 20);
}
}
public class AnnotationTest {
public static void main(String[] args) {
final ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AnnotationConfig.class);
final Person person = applicationContext.getBean(Person.class);
System.out.println(person);
}
}
测试结果
Person{name='xiaomin', age=20}
我们也可以通过ApplicationContext的一些方法来获取容器里面的bean信息,比如哦我们可以获取Person这个bean在IOC容器里面的名字,也是相当于xml配置文件里面标签里面的id属性。
public class AnnotationTest {
public static void main(String[] args) {
final ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AnnotationConfig.class);
final Person person = applicationContext.getBean(Person.class);
System.out.println(person);
final String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
Arrays.stream(beanNamesForType).forEach(System.out::println);
}
}
其实获取的Peron在IOC容器的名字就是@Bean注解的方法名称。
测试结果
Person{name='xiaomin', age=20}
person
Spring注解的方式默认是以@Bean注解的方法名作为bean的默认id,如果我们不想要方法名来作为bean的id,我们可以在@Bean这个注解的value属性来进行指定。
我们可以在配置类中写包扫描。
@ComponentScan相当于xml配置文件里面的
@Configuration
@ComponentScan("com.atguigu.bean")
public class AnnotationConfig {
@Bean({"person1"})
public Person person() {
return new Person("xiaomin", 20);
}
}
所有com.atguigu.bean包路径下、子包路径下加了@Controller、@Service、@Repository、@Component注解的类都会被注册到IOC容器中称为bean对象。
默认注册的组件都是单例的。
public class AnnotationTest {
public static void main(String[] args) {
final ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AnnotationConfig.class);
final Person person = applicationContext.getBean(Person.class);
final Person person1 = (Person)applicationContext.getBean("person");
System.out.println(person1 == person);
}
}
测试结果
true
说明这个bean的实例是单例的;
@Configuration
@ComponentScan("com.atguigu.bean")
public class AnnotationConfig {
// singleton:单实例的
// prototype:原型(多实例的)
// request:同一次请求创建一个实例
// session:同一个session创建一个实例
@Scope("prototype")
@Bean
public Person person() {
return new Person("xiaomin", 20);
}
}
当bean的作用域为多实例的时候,IOC容器启动的时候不会去创建bean的实例,而是在使用的时候才去创建bean的实例。