【Java】Spring之基于注释的容器配置(四)
注释是否比配置Spring的XML更好?
基于注释的配置的引入引发了这种方法是否比XML“更好”的问题。答案是每种方法都有其优点和缺点,通常,由开发人员决定哪种策略更适合他们。由于它们的定义方式,注释在其声明中提供了大量上下文,从而导致更短更简洁的配置。但是,XML擅长在不触及源代码或重新编译它们的情况下连接组件。一些开发人员更喜欢将布线靠近源,而另一些开发人员则认为注释类不再是POJO,而且配置变得分散且难以控制。
无论选择如何,Spring都可以兼顾两种风格,甚至可以将它们混合在一起。
注意:
注释注入在XML注入之前执行。因此,XML配置会覆盖通过这两种方法连接的属性的注释。
Spring开启注释
1、<context:annotation-config> :是用于激活那些已经在spring容器里注册过的bean(无论是通过xml的方式还是通过package sanning的方式)上面的注解。
2、<context:component-scan>:除了具有<context:annotation-config>的功能之外,<context:component-scan>还可以在指定的package下扫描以及注册javabean 。
Spring常用注释
@Required
@Required注释适用于bean属性setter方法,此批注指示必须在配置时通过bean定义中的显式属性值或通过自动装配填充受影响的bean属性。如果尚未填充受影响的bean属性,则容器将引发异常。
public class SimpleMovieLister { private MovieFinder movieFinder; @Required
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
} // ...
}
@Autowired
可以将@Autowired注释应用于构造函数,还可以将@Autowired注释应用于“传统”setter方法,还可以将注释应用于具有任意名称和多个参数的方法
public class MovieRecommender { private final CustomerPreferenceDao customerPreferenceDao; @Autowired
private MovieCatalog movieCatalog; @Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
} @Autowired(required = false)
public void setMovieFinder(MovieCatalog movieCatalog) {
this.movieCatalog = movieCatalog;
} // ...
}
@Primary
由于按类型自动装配可能会导致多个候选人,因此通常需要对选择过程进行更多控制。实现这一目标的一种方法是使用Spring的@Primary
注释。@Primary
表示当多个bean可以自动装配到单值依赖项时,应该优先选择特定的bean。如果候选者中只存在一个主bean,则它将成为自动装配的值。
@Configuration
public class MovieConfiguration { @Bean
@Primary
public MovieCatalog firstMovieCatalog() { ... } @Bean
public MovieCatalog secondMovieCatalog() { ... } // ...
}
@Resource
@Resource采用名称属性。默认情况下,Spring将该值解释为要注入的bean名称。换句话说,它遵循按名称语义,如以下示例所示:
如果未明确指定名称,则默认名称是从字段名称或setter方法派生的。如果是字段,则采用字段名称。在setter方法的情况下,它采用bean属性名称
public class SimpleMovieLister { private MovieFinder movieFinder; @Resource(name="myMovieFinder")
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
@PostConstruct 和 @PreDestroy
一个bean进行初始化时,回调@PostConstruct注释的方法
一个bean进行销毁时,回调@PreDestroy注释的方法
public class CachingMovieLister { @PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization...
} @PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction...
}
}
@Component
表示一个带注释的类是一个“组件”,成为Spring管理的Bean。当使用基于注解的配置和类路径扫描时,这些类被视为自动检测的候选对象。同时
@Component是任何Spring管理组件的通用构造型。@Repository,@Service和,@Controller是@Component更具体的用例的专业化(分别在持久性,服务和表示层)。因此,您可以来注解你的组件类有 @Component,但是,通过与注解它们@Repository,@Service或者@Controller ,你的类能更好地被工具处理,或与切面进行关联。
package com.test.spring.beanannotation; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; // @Component("beanAnno")
@Component
// @Scope("prototype")
@Scope
public class BeanAnnotation { public void say(String arg) {
System.out.println("BeanAnnotation:" + arg);
} public void myHashCode() {
System.out.println("BeanAnnotation:" + this.hashCode());
} }
@Component还是一个元注解。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service { // ....
}
@Configuration
声明当前类是一个配置类(相当于一个Spring配置的xml文件)
@ComponentScan
自动扫描指定包
@Configuration
@ComponentScan(basePackages = "org.example")
public class AppConfig {
...
}
简洁起见,前面的示例可能使用value了注释的属性(即@ComponentScan("org.example"))
替代方法使用XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="org.example"/> </beans>
@Bean 和 @Configuration
Spring的新Java配置支持中的中心工件是 @Configuration注释类和@Bean注释方法。
该@Bean注释被用于指示一个方法实例,配置和初始化为通过Spring IoC容器进行管理的新对象。对于那些熟悉Spring的<beans/>XML配置的人来说,@Bean注释与<bean/>元素扮演的角色相同。你可以@Bean在任何Spring中使用-annotated方法 @Component。但是,它们最常用于@Configuration豆类。
对类进行注释@Configuration表明其主要目的是作为bean定义的来源。此外,@Configuration类允许通过调用@Bean同一类中的其他方法来定义bean间依赖关系。最简单的@Configuration类如下:
@Configuration
public class AppConfig { @Bean
public MyService myService() {
return new MyServiceImpl();
}
}
上面的AppConfig类等效于以下Spring <beans/>XML:
<beans>
<bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>
还可以@Bean
使用接口(或基类)返回类型声明您的方法
@Bean
注释支持指定任意初始化和销毁回调方法
public class BeanOne { public void init() {
// initialization logic
}
} public class BeanTwo { public void cleanup() {
// destruction logic
}
} @Configuration
public class AppConfig { @Bean(initMethod = "init")
public BeanOne beanOne() {
return new BeanOne();
} @Bean(destroyMethod = "cleanup")
public BeanTwo beanTwo() {
return new BeanTwo();
}
}
@ImportResource
虽然Spring提倡零配置,但是还是提供了对xml文件的支持,这个注解就是用来加载xml配置的。例:@ImportResource({"classpath"})
@Value
值得注入。经常与Sping EL表达式语言一起使用,注入普通字符,系统属性,表达式运算结果,其他Bean的属性,文件内容,网址请求内容,配置文件属性值等等
package com.test.spring.beanannotation.javabased; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource; @Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig { @Value("${jdbc.url}")
private String url;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.username}")
private String username; @Bean
public MyDriverManager myDriverManager() {
return new MyDriverManager(url, username, password);
} }
@Profile
通过@Profile 注释,您可以指示当一个或多个指定的配置文件处于活动状态时,组件符合注册条件。使用前面的示例,按如下方式重写配置:
@Configuration
@Profile("development")
public class StandaloneDataConfig { @Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.addScript("classpath:com/bank/config/sql/test-data.sql")
.build();
}
}
如果@Configuration标记了类,则除非一个或多个指定的配置文件处于活动状态,否则将绕过与该类关联的@Profile所有@Bean方法和 @Import注释。如果a @Component或@Configurationclass被标记@Profile({"p1", "p2"}),则除非已激活配置文件'p1'或'p2',否则不会注册或处理该类。如果给定的配置文件以NOT运算符(!)作为前缀,则仅在配置文件未激活时才注册带注释的元素。例如,@Profile({"p1", "!p2"})如果配置文件“p1”处于活动状态或配置文件“p2”未激活,则会发生注册
【Java】Spring之基于注释的容器配置(四)的更多相关文章
- Spring 框架的概述以及Spring中基于XML的IOC配置
Spring 框架的概述以及Spring中基于XML的IOC配置 一.简介 Spring的两大核心:IOC(DI)与AOP,IOC是反转控制,DI依赖注入 特点:轻量级.依赖注入.面向切面编程.容器. ...
- 10 Spring框架--基于注解的IOC配置
1.工程环境搭建 2.基于注解的IOC配置 IOC注解的分类 (1)用于创建对象的 他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的@Component: 作用: ...
- spring-第十七篇之spring AOP基于注解的零配置方式
1.基于注解的零配置方式 Aspect允许使用注解定义切面.切入点和增强处理,spring框架可以识别并根据这些注解来生成AOP代理.spring只是用了和AspectJ 5一样的注解,但并没有使用A ...
- Spring5参考指南:基于注解的容器配置
文章目录 @Required @Autowired @primary @Qualifier 泛型 @Resource @PostConstruct和@PreDestroy Spring的容器配置可以有 ...
- spring的基于xml的AOP配置案例和切入点表达式的一些写法
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.spr ...
- Spring IOC之基于注解的容器配置
Spring配置中注解比XML更好吗?基于注解的配置的介绍提出的问题是否这种途径比XML更好.简单来说就是视情况而定. 长一点的答案是每一种方法都有自己的长处也不足,而且这个通常取决于开发者决定哪一种 ...
- 【Spring】基于@Aspect的AOP配置
Spring AOP面向切面编程,可以用来配置事务.做日志.权限验证.在用户请求时做一些处理等等.用@Aspect做一个切面,就可以直接实现. · 本例演示一个基于@Aspect的小demo 1. ...
- spring的基于注解的IOC配置
1.配置文件配置 <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http: ...
- JAVA Spring Cloud 注册中心 Eureka 相关配置
转载至 https://www.cnblogs.com/fangfuhai/p/7070325.html Eureka客户端配置 1.RegistryFetchIntervalSecon ...
随机推荐
- c风格的字符串
c风格的字符串的标注库 #include <cstring> 使用c 风格的字符串,牢记,其必须以null为结束标志 如 char ca[]={'c','+','='}; cout< ...
- python笔记39-unittest框架如何将上个接口的返回结果给下个接口适用(面试必问)
前言 面试必问:如何将上个接口的返回结果,作为下个接口的请求入参?使用unittest框架写用例时,如何将用例a的结果,给用例b使用. unittest框架的每个用例都是独立的,测试数据共享的话,需设 ...
- 史上最完整promise源码手写实现
史上最完整的promise源码实现,哈哈,之所以用这个标题,是因为开始用的标题<手写promise源码>不被收录 promise自我介绍 promise : "君子一诺千金,承诺 ...
- lambda()函数
lambda lambda原型为:lambda 参数:操作(参数) lambda函数也叫匿名函数,即没有具体名称的函数,它允许快速定义单行函数,可以用在任何需要函数的地方.这区别于def定义的函数. ...
- 14-Flutter移动电商实战-ADBanner组件的编写
拨打电话的功能在app里也很常见,比如一般的外卖app都会有这个才做.其实Flutter本身是没给我们提供拨打电话的能力的,那我们如何来拨打电话那? 1.编写店长电话模块 这个小伙伴们一定轻车熟路了, ...
- SpringBoot之使用Druid连接池,SQL监控和spring监控
项目结构 1.引入maven依赖 <dependencies> <dependency> <groupId>org.springframework.boot< ...
- Log4net 数据库存储(四)
1.新建一个空的ASP.Net 空项目,然后添加Default.aspx窗体 2.添加配置文件:log4net.config <?xml version="1.0" enco ...
- 数组(定义、遍历、冒泡排序、合并和Join 方法)
一.数组的定义 1.理解:数组指一组数据,有序的数据,可以一次性存储多个数据,将多个元素(通常统一类型)按照一定的顺序排列放到一个集合里 2.通过构造函数创建数组: var 数组名=new Arrar ...
- Mongo 安装及基本操作
一. 安装 Mongo文档: https://docs.mongodb.com/v3.6/administration/install-enterprise-linux/ Linux mongo的配置 ...
- 如何解决数据类别不平衡问题(Data with Imbalanced Class)
类别不平衡问题是指:在分类任务中,数据集中来自不同类别的样本数目相差悬殊. 类别不平衡问题会造成这样的后果:在数据分布不平衡时,其往往会导致分类器的输出倾向于在数据集中占多数的类别:输出多数类会带来更 ...