摘要

Spring4 以后,官方推荐我们使用Java Config来代替applicationContext.xml,声明将Bean交给容器管理。
在Spring Boot中,Java Config的使用也已完全替代了applicationContext.xml。实现了xml的零配置。所以无论从Spring的演进,还是学习Spring Boot的需要,都应该深入学习Spring Java Config的使用方法。这篇文章主要从以下几个方面进行介绍:

  • Spring java Config 入门程序
  • bean标签的使用
  • bean的依赖
  • 自动扫描
  • import 和 importResource
  • properties文件的加载及占位
  • profile

Spring Java Config入门介绍及简单程序

回顾以前的applicationContext.xml配置方式,我们会将需要使用bean通过xml的形式来配置,那么Java Config的方式,不需要多思考,就可以判断我们应该将bean配置在一个Java文件中,而且这个Java文件应当被Spring容器所识别。我们看如下这个例子:

创建一个bean类
public class SomeBean {
public void doWork() {
System.out.println("do work...");
}
}

其中,doWork是逻辑方法。

创建一个Config类
@Configuration
public class Config {
@Bean
public SomeBean someBean() {
return new SomeBean();
}
}

需要注意的是,我们在config类上添加了一个@configuration的注解,见名知意,我们可以理解为Spring中的配置类。在返回值为SomeBeansomeBean方法上我们添加了一个@Bean注解,也不难理解,返回的new SomeBean对象将交由Spring容器进行管理。

测试
public class Test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
SomeBean sb = context.getBean(SomeBean.class);
sb.doWork();
}
}

这里,我们创建了一个AnnotationConfigApplicationContext对象,传入了Config.class后,得到了SomeBean对象。

do work...

以上就是Spring Java Config 配置bean的最简单的程序,对不喜欢xml配置的开发人员还是比较有优势的。
我们知道,在xml中,一般是这样配置的:

<bean id="someBean" class="com.springboot.javaconfig.SomeBean" initMethod="init" destroyMethod="destroy" ref="otherBean" scope="singlon"

一个完整的bean配置包括了 id,class,initMethod,destroyMethodref,scope

那么,在Java Config如何配置这些属性呢?其实也是很简单的,我们修改第一个例子的代码:

public class SomeBean {

    private void init() {
System.out.println("init...");
} public void doWork() {
System.out.println("do work...");
} private void destroy() {
System.out.println("destroy...");
} }

增加了init,destroy方法。

@Configuration
public class Config { @Bean(initMethod = "init",destroyMethod = "destroy")
public SomeBean someBean() {
return new SomeBean();
}
}

在bean注解上,属性指向对应的方法名。

public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
SomeBean sb1 = context.getBean(SomeBean.class);
System.out.println(sb1); SomeBean sb2 = context.getBean(SomeBean.class);
System.out.println(sb2);
context.close();
}
}

输出结果为:

init...
com.spring.SomeBean@16022d9d
com.spring.SomeBean@16022d9d
destroy...

从这个程序我们可以看出如下信息:

  • init,destroy方法都在相应的阶段被调用
  • 两次创建的SomeBean实例指向同一个地址,说明Spring容器给我们创建的SomeBean对象时单例的。
其它

如果希望创建了一个多例的bean,可以这样书写:

@Scope("prototype")
public class SomeBean {
}

如果希望使用id和class共同查找bean,可以这样书写:

SomeBean sb = context.getBean("someBean",SomeBean.class);

需要特别注意的是,Spring默认使用Config中的函数名作为该bean的id。

bean的依赖

在xml中,我们使用value来配置注入简单值,ref来配置注入其他对象,那么在Java Config中如何实现呢?我们来继续编写代码:

新建一个bean类
public class OtherBean {

}
修改SomeBean和Config类
public class SomeBean {

    @Autowired
private OtherBean otherBean; public void sayHello() {
System.out.println(otherBean);
} }
@Configuration
public class Config { @Bean
public SomeBean someBean() {
return new SomeBean;
} @Bean
public OtherBean otherBean () {
return new OtherBean();
}
}

此时,我们将OtherBean纳入spring容器进行管理,在SomeBean类中对OtherBean的实例进行注入。得到结果:

com.spring.OtherBean@51b279c9

由此,实现了Java Config中的依赖注入,只不过也就是将需要依赖的bean也加入Config类用bean以修饰。
当然,我们也可以不使用@AutoWired标签,而通过set方法注入。


@Configuration
public class Config { @Bean
public SomeBean someBean(OtherBean otherBean) {
SomeBean someBean = new SomeBean();
// 1
someBean.setOtherBean(new OtherBean());
// 2
someBean.setOtherBean(otherBean()); // 3
someBean.setOtherBean(otherBean);
return someBean;
} @Bean
public OtherBean otherBean () {
return new OtherBean();
}
}

set注入方法比较多,可以自行创建一个OtherBean对象,因为都在Config类中,也可以调用otherBean()方法,也可以在参数列表中进行传入,参数名要使用OtherBean的方法名。因为OtherBean类型的可能有多个对象。

Java Config 和 注解配置混用

我们知道,spring为我们提供了诸如@component,@controller,@service,@repositroy这类标签,它们增加了类的语义,然后将对应的类加入到了spring容器进行管理,也是避免了在xml中去配置。将Java Config和注解配置混用是我们在日常开发中经常使用的方式,我们来看如下代码,模拟MVC三层架构:

LoginDAO:
@Repository
public class LoginDAO {
public void login() {
System.out.println("login...");
}
}
LoginService
@Service
public class LoginService { @Autowired
private LoginDao loginDao; public void login() {
loginDao.login();
}
}
LoginController
@RequestMapping("/user")
@RestController
public class LoginController { @Autowired
private LoginService loginService; @RequestMapping(path = "/login",method = RequestMethod.POST)
public void login() {
loginService.login();
}
}
Java Config
@ComponentScan(basePackages = "com.spring")
@Configuration
public class Config {
}
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); LoginController controller = context.getBean("loginController",LoginController.class); controller.login();
}
}

输出结果:

login...

解读:我们并没有将LoginDAO,LoginService,LoginController纳入Config,用@Bean修饰,而是使用了注解配置,在Config类中通过ComponentScan标签,将它们纳入sping容器。通过测试, 我们发现,Java Config 和 注解配置的混合使用时可行的。

Java Config 和 applicationContext.xml混用

有时候,我们会遇到必须使用xml配置的情况,这时候,我们可以这样来操作:

创建applicationContext.xml文件
<bean id="xmlBean" class="com.spring.XMLBean"/>
修改Config
@ImportResource("com/spring/applicationContext.xml")
@ComponentScan(basePackages = "com.spring")
@Configuration
public class Config {
}

运行结果:

com.spring.XMLBean@7bb58ca3

Config类上使用@ImportResource标签,就可以将在xml配置的bean引入到spring容器。

占位符配置

自定义datasource
public class DataSource {
private String url;
private String driverClass;
private String userName;
private String password;
// get()
// set()
// constructor()
}

在xml中,我们配置datasource时往往将连接信息封装在db.properties中:

driverClass=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/my-database
username=root
password=root

在xml中使用占位的方式来获取:

<context:property-placeholder location="com/spring/db.properties"/>
<bean id="dataSource" class="com.spring.DataSource">
<property name="url" value="${url}"/>
<property name="driverClass" value="${driverClass}"/>
<property name="userName" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
测试
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
DataSource dataSource = context.getBean("dataSource",DataSource.class);
System.out.println(dataSource);
}
}

输出结果:

DataSource{url='jdbc:mysql://localhost:3306/test', driverClass='com.mysql.jdbc.driver', userName='root', password='root'}

那么如何在Config中解读占位配置呢?继续编写代码:

以示区分,我们修改一下,db.properties:
driverClass=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/test
user=admin
password=admin
修改Config
//@ImportResource("com/spring/applicationContext.xml")
@PropertySource("com/spring/db.properties")
@ComponentScan(basePackages = "com.spring")
@Configuration
public class Config { @Autowired
private Environment env; @Bean
public DataSource dataSource() {
return new DataSource(env.getProperty("url"),env.getProperty("driverClass"),
env.getProperty("user"),env.getProperty("password"));
}
}

此时,我们先是去掉了@ImportResource标签,因为已经不需要在xml中配置了,又使用了一个新的标签@PropertySource,来加载db,properties文件,然后又注入了一个env对象,Environment类继承了PropertyResolver接口,专门用来解析properties。

输出结果:

DataSource{url='jdbc:mysql://localhost:3306/test', driverClass='com.mysql.jdbc.driver', user='admin', password='admin'}

可以看到,加载properties文件,在Spring Java Config也提供了支持。

Spring中的资源文件框架——Resource的更多相关文章

  1. springboot jar包运行中获取资源文件

    1. 今天晚上写了一个程序,基于Spring boot的一个小网站,发现使用FileUtils.class.getResource(path)来获取jar包中的资源文件并不能成功,其路径很奇怪 fil ...

  2. 【解惑】深入jar包:从jar包中读取资源文件

    [解惑]深入jar包:从jar包中读取资源文件 http://hxraid.iteye.com/blog/483115 TransferData组件的spring配置文件路径:/D:/develop/ ...

  3. java 从jar包中读取资源文件

    在代码中读取一些资源文件(比如图片,音乐,文本等等),在集成环境(Eclipse)中运行的时候没有问题.但当打包成一个可执行的jar包(将资源文件一并打包)以后,这些资源文件找不到,如下代码: Jav ...

  4. (转)java 从jar包中读取资源文件

    (转)java 从jar包中读取资源文件 博客分类: java   源自:http://blog.csdn.net/b_h_l/article/details/7767829 在代码中读取一些资源文件 ...

  5. java基础知识3--如何获取资源文件(Java中获取资源文件的url)

    java开发中,常见的resource文件有:.xml,.properties,.txt文件等,后台开发中经常用到读取资源文件,处理业务逻辑,然后返回结果. 获取资源文件的方法说明getResourc ...

  6. 深入jar包:从jar包中读取资源文件getResourceAsStream

    一.背景 我们常常在代码中读取一些资源文件(比如图片,音乐,文本等等). 在单独运行的时候这些简单的处理当然不会有问题.但是,如果我们把代码打成一个jar包以后,即使将资源文件一并打包,这些东西也找不 ...

  7. Android开发---如何操作资源目录中的资源文件

    效果图: 1.activity_main.xml <?xml version="1.0" encoding="utf-8"?> <Linear ...

  8. robot framework学习笔记之一 资源文件(Resource)和外部资源(External Resources)

    一.资源文件(Resource) 测试套件主要是存放测试案例,资源文件主要是用来存放用户关键字. 添加资源    在目录型的Project/Test Suite下单击鼠标右键,选择『New Resou ...

  9. [Java基础] 深入jar包:从jar包中读取资源文件

    转载: http://hxraid.iteye.com/blog/483115?page=3#comments 我们常常在代码中读取一些资源文件(比如图片,音乐,文本等等).在单独运行的时候这些简单的 ...

随机推荐

  1. DevOps - DevOps精要 - 歧途

    前言 如果在实施DevOps的过程中,周围没有一个人支持你,也没有得到领导和团队成员的理解: 如果在采用DevOps的工具和方法之后,难以获得明显的效率提升,甚至得到了不少的消极反馈: 那就需要反省一 ...

  2. 向多个git仓库提交

    查看所有远程仓库 为了不用每次输密码,可以先配置ssh key 查看 添加远程仓库 git remote add origin1 git@other:YYYYYYYYYY/AA.git 向新的代码仓库 ...

  3. pod 常用指令

    //只安装新增的库,已经安装的库不更新 pod install --verbose --no-repo-update //只更新指定库名的第三个库,其他库不更新 pod update 库名 --ver ...

  4. 乐字节Java之file、IO流基础知识和操作步骤

    嗨喽,小乐又来了,今天要给大家送上的技术文章是Java重点知识-IO流. 先来看看IO流的思维导图吧. 一. File 在Java中,Everything is Object!所以在文件中,也不例外! ...

  5. 软件素材---linux C语言:linux下获取可执行文件的绝对路径--getcwd函数

    //头文件:#include <unistd.h> //定义函数:char * getcwd(char * buf, size_t size); //函数说明:getcwd()会将当前的工 ...

  6. e.g. i.e. etc. et al. w.r.t. i.i.d.英文论文中的缩写语

    e.g. i.e. etc. et al. w.r.t. i.i.d. 用法:, e.g., || , i.e., || , etc. || et al., || w.r.t. || i.i.d. e ...

  7. [转帖]ORM框架的前世今生

    ORM框架的前世今生 https://www.cnblogs.com/7tiny/p/9551754.html 目录 一.ORM简介二.ORM的工作原理三.ORM的优缺点四.常见的ORM框架 一.OR ...

  8. Jenkins+maven+gitlab自动化部署之构建Java应用(五)

    前面几篇文章介绍jenkins部署以及配置,接下来我们,就介绍下如何使用jenkins发布应用. 1)新建项目 jenkins首页,点击左上新建任务,出现下图,填写对应信息,然后点击确定: 2)项目参 ...

  9. go select 使得一个 goroutine 在多个通讯操作上等待。

    select 语句使得一个 goroutine 在多个通讯操作上等待. select 会阻塞,直到条件分支中的某个可以继续执行,这时就会执行那个条件分支.当多个都准备好的时候,会随机选择一个. pac ...

  10. Luogu5307 [COCI2019] Mobitel 【数论分块】【递推】

    题目分析: 对于向上取整我们总有,$\lceil \frac{\lceil \frac{n}{a} \rceil}{b} \rceil = \lceil \frac{n}{a*b} \rceil$这个 ...