一.注解定义bean
1.在类前加入@Component标签指定
(1)业务层使用@Service(2)数据层使用@Repository(3)控制层使用@Controller
(作用相同但是有利于开发阅读)
定义一个注解类
@Component
public class Impl implements (接口){
}
2.在配置文件中扫描
<context:component-scan base-package="扫描的位置">
二.纯注解开发
1.用配置类取代配置文件
//注解形式定义配置类
@Configuration
//扫描文件
@ComponentScan("扫描包的位置")
//加载properties文件
@PropertySources("properties文件名称")
public class SpringConfig(){
}
2.加载配置类
public static void main (String[] arg){
ApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class);
}
三.注解形式配置bean的属性
//定义类为注解类型的bean
@Conponent
//定义开发是单例还是非单例
@Scope("")
//用在inti方法前替代inti-method
@PostConstruct
//用在destory前替代destory-method
@PreDestroy
四.注解开发(依赖注入)
自动装配(可以不要set方法)(暴力反射)
1.引用类型注入
@Autowired
//默认按照类型注入,如果有两个相同类型的可以使用
@Qualifier("")
//进行类型的指定
2.普通类型注入
@Value("")
五.管理第三方bean
方法一:常用
@import({第三方bean.class})
方法二:用@Configuration修饰,并且通过ComponentScan精准扫描(一般不用)