Spring注解开发
注解 |
说明 |
@Component |
使用在类上用于实例化Bean |
@Controller |
使用在web层类上用于实例化Bean |
@Service |
使用在service层类上用于实例化Bean |
@Repository |
使用在dao层类上用于实例化Bean |
@Autowired |
使用在字段上用于根据类型依赖注入 |
@Qualifier |
结合@Autowired一起使用用于根据名称进行依赖注入 |
@Resource |
相当于@Autowired+@Qualifier,按照名称进行注入 |
@Value |
注入普通属性 |
@Scope |
标注Bean的作用范围 |
@PostConstruct |
使用在方法上标注该方法是Bean的初始化方法 |
@PreDestroy |
使用在方法上标注该方法是Bean的销毁方法 |
一、@Configuration
@Configuration是类级别的注解,指示对象是 Bean 定义的源。
@Bean注解用于表示一个方法实例化、配置和初始化一个由 Spring IoC 容器管理的新对象。最常与@Configuration 一起使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Person { private String name; private Integer age; public Person() {} public Person(String name, Integer age) { this.name = name; this.age = age; } set/get/toString... }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| package com.lan.config;
import com.lan.pojo.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.stereotype.Controller;
@Configuration
@ComponentScan(value = "com.lan", excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {Controller.class}) }) public class MainConfig {
@Bean public Person person() { System.out.println("给容器中添加Person..."); return new Person("zhangsan", 20); }
}
|
1 2 3 4 5 6 7
| AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class); System.out.println("ioc容器创建完成..."); String[] definitionNames = app.getBeanDefinitionNames(); for (String name : definitionNames) { System.out.println(name); }
|
注:可根据过滤规则,过滤指定的组件(这里指定的是Controller组件)
二、懒加载@Lazy:
如果我们想要 Spring 在启动的时候延迟加载 bean,即在调用某个 bean 的时候再去初始化,那么就可以使用 @Lazy 注解。
测试结果:
没加懒加载的运行结果:
1 2 3 4
| 给容器中添加Person... ioc容器创建完成...
Process finished with exit code 0
|
加了懒加载的运行结果:
1 2 3
| ioc容器创建完成... Process finished with exit code 0
|