【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++继承层次中的函数调用
```cpp //============================================================================ // Name : TS.c ...
- Linux 设置系统编码
1.locale -a查看系统支持的语言2.进入etc/sysconfig/3.编辑i18n4.修改lang 5.设置完成后刷新:i18n source /etc/sysconfig/i18n
- Codeforces I. Vessels(跳转标记)
题目描述: Vessels time limit per test 2 seconds memory limit per test 256 megabytes input standard input ...
- 基于springboot2.x集成缓存注解及设置过期时间
添加以下配置信息: /** * 基于注解添加缓存 */ @Configuration @EnableCaching public class CacheConfig extends CachingCo ...
- Centos7-Gnome安装
查看grouplist yum grouplist 安装gnome yum groupinstall "GNOME Desktop" root用户权限下,设置centos系统默认的 ...
- Navicat 的使用 —— 快捷键
名称 功能 备注 Ctrl+Q 打开查询窗口 Ctrl+/ 注释sql语句 Ctrl+R 运行查询窗口的sql语句 Ctrl+Shift+R 只运行选中的sql语句 F6 打开一 ...
- WinDbg常用命令系列---!cppexr
!cppexr 简介 !cppexr显示C++异常记录的内容. 使用形式 !cppexr Address 参数 Address指定要显示的C++异常记录的地址. 支持环境 Windows 2000 E ...
- 关于redash 自定义可视化以及query runner 开发的几篇文章
以下是几篇关于如如何编码redash 自定义可视化插件以及query runner 的连接,很有借鉴价值 参考连接 https://discuss.redash.io/t/how-to-create- ...
- 使用nginx 正向代理暴露k8s service && pod ip 外部直接访问
有时在我们的实际开发中我们希望直接访问k8s service 暴露的服务,以及pod的ip 解决方法,实际上很多 nodeport ingress port-forword 实际上我们还有一种方法:正 ...
- 集成omnibus-ctl 开发一个专业的软件包管理工具
前边有转发过来自chef 团队的一篇omnibus-ctl 介绍文章,以下尝试进行项目试用 就是简单的集成,没有多少复杂的操作 环境准备 ruby ruby 使用2.6.3 使用 rbenv 安装,可 ...