概述
引入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
spring-context jar包是Spring核心环境依赖包。
@Configuration注解方式配置bean
- 首先我们写一个配置类,等同于xml配置文件
/**
* @Configuration注解告诉Spring这是一个配置类,类似Spring中的xml文件
*/
@Configuration
public class AnnotationConfig {
@Bean
public Person person() {
return new Person("xiaomin", 20);
}
}
- 测试AnnotationConfigApplicationContext的用法
new一个AnnotationConfigApplicationContext对象,以前使用的是ClassPathXmlApplicationContext对象(构造函数里面传的是配置文件的位置),现在使用AnnotationConfigApplicationContext对象的构造函数里面传的是配置类的类型。
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自动扫描组件并注册
我们可以在配置类中写包扫描。
@ComponentScan相当于xml配置文件里面的<context:component-scan base-package=“com.atguigu.bean”/>
@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对象。
@Scope设置组件作用域
默认注册的组件都是单例的。
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的实例是单例的;
@Scope用法
@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的实例。
参考
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/100002.html