在xml中配置bean有如下配置,非常麻烦,在新spring和springboot中都是用注解开发
@Repository @Service @Controller @Configuration都包含元注解@Component@Component只需要在类上加注解,不用再去xml中配bean标签@Autowired @Qualifier @Resource则是注入,替代了bean标签的ref功能@Repository是写在Dao层的,@Mapper是没有注入功能的 注入,交给Spring的IOC容器进行管理
@Component可以设置一个value值,即id,可以搭配@Qualifier交给Spring管理的类才可以调用Spring IOC的注解,换言之,例如:如果是一个普通类,则没办法@Autowired和被@Autowired@Repository @Service @Controller @Configuration功能基本一致,但是为了解耦且易于分辨,在不同层用不同的注解 @Autowired注入
像Dao层,Service层,这些 类名=id 的组件是唯一的,换言之不需要用@Qualifier来区分像自定义的bean,在xml文件中进行配置的bean,可能存在同类不同bean(不同id)的情况,需要**@Qualifier+@Autowired来区分+注入**@Resource() = @Qualifier()+@Autowired @Scope作用域
可以写在@Bean上,也可以写在@Component上
前者作用在方法上,细粒度;后者作用在类上,粗粒度。都是注入到容器中,并且可以被使用
同样,要使用这个注解,该类本身也必须是要被注入到容器中的
前者相当于xml配置中的init-method,后者相当于destroy-method
@PostConstruct
public void bean初始化的连带方法(){}
Spring新注解
@Configuration核心配置类
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的
类的方式代替文件,注解的方式代替标签
核心配置类只有一个,要导入其他配置类中的bean则需要@import({})导入其他非核心配置类
@ComponentScan扫描包默认当前类的包下,也可以自己配置代替xml中的context:component-scan base-package = “” @PropertySource读取自定义配置
@ConfigurationProperties会加载配置文件application.yml或application.properties配置中的属性;
但是如果我们需要自己单独定义的属性文件的时候, 就要用到 自己指定属性源了: @PropertySource
演示案例
普通类使用IOC容器中的bean方式一:@Component注入Spring容器,交给Spring托管,可以使用Spring的注解例如@Autowired
方式二:实现ApplicationContextAware接口,写一个工具类
为什么普通类不能直接@Autowiredspring基于注解的普通类怎么调用@Services注解的service方法,需要一些先决条件:
1、如果你想用@autowired,那么这个类本身也应该是在spring的管理下的,即你的UserLogUtil也要标注为一个component(或Service),这样spring才知道要注入依赖;
2、或者,不标注为@Component的话,此时不能通过@autowired来注入依赖,只能通过ApplicationContext来取得标注为Service的类:
UserLogService service = ApplicationContext.getBean(UserLogService.class)。



