资讯专栏INFORMATION COLUMN

如何把Spring Boot 项目变成一个XML配置的Spring项目

eechen / 3151人阅读

摘要:需要弄清楚自己项目的依赖关系,在中第三方包如何初始化。打包会把项目和所依赖的包打包成一个大包,直接运行这个包就可以。依赖包使用下面的配置帮你把所有的依赖包复制到目录下,方便我们部署或者是测试时复制依赖包。

现在大家都追赶新的技术潮流,我来逆行一下。

其实Spring Boot 隐藏了大量的细节,有大量的默认配置,其实通过xml配置的方式也可以达到和Spring Boot一样的效果。

Profile

在Spring Boot项目中我们通过application.properties中的设置来配置使用哪个配置文件application-dev.properties,application-prod.properties等等

</>复制代码

  1. spring.profiles.active=dev

Spring 3.0以后就包含了Profile功能,在xml中可以这么写,不过所有的bean需要显式的配置。需要弄清楚自己项目的依赖关系,在Spring中第三方包如何初始化。

</>复制代码

在Spring Boot中大量的Jave Bean都包含了默认初始化的功能,只需要配置预先设置好的属性名称,但是在xml中需要显式的初始化Bean,并且可以在初始化的时候用Placeholder来配置。

Environment

在 Spring Boot 项目中application.propertiesapplication-xxx.properties 中的变量会自动放到 Environment中,并且可以通过@Value直接注入到变量中。

如果使用 ClassPathXmlApplicationContext 初始化项目,可以看到源代码里 Environment 是一个 StandardEnvironment 实例,仅仅包含系统变量和环境变量,为了把application-xxx.properties放到 Environment 当中我们需要扩展一下 ClassPathXmlApplicationContext,下面是CustomApplicationContextCustomEnvironment

</>复制代码

  1. import org.springframework.context.support.ClassPathXmlApplicationContext;
  2. import org.springframework.core.env.ConfigurableEnvironment;
  3. public class CustomApplicationContext extends ClassPathXmlApplicationContext {
  4. public CustomApplicationContext(){
  5. super();
  6. }
  7. public CustomApplicationContext(String configLocation) {
  8. super(new String[]{configLocation}, true, null);
  9. }
  10. @Override
  11. public ConfigurableEnvironment createEnvironment() {
  12. return new CustomEnvironment();
  13. }
  14. }

</>复制代码

  1. import org.springframework.core.env.MutablePropertySources;
  2. import org.springframework.core.env.PropertySource;
  3. import org.springframework.core.env.StandardEnvironment;
  4. import org.springframework.core.io.DefaultResourceLoader;
  5. import org.springframework.core.io.Resource;
  6. import org.springframework.core.io.support.ResourcePropertySource;
  7. import java.io.IOException;
  8. public class CustomEnvironment extends StandardEnvironment {
  9. private static final String APPCONFIG_PATH_PATTERN = "classpath:application-%s.properties";
  10. @Override
  11. protected void customizePropertySources(MutablePropertySources propertySources) {
  12. super.customizePropertySources(propertySources);
  13. try {
  14. propertySources.addLast(initResourcePropertySourceLocator());
  15. } catch (IOException e) {
  16. logger.warn("failed to initialize application config environment", e);
  17. }
  18. }
  19. private PropertySource initResourcePropertySourceLocator() throws IOException {
  20. String profile = System.getProperty("spring.profiles.active", "dev");
  21. String configPath = String.format(APPCONFIG_PATH_PATTERN, profile);
  22. System.out.println("Using application config: " + configPath);
  23. Resource resource = new DefaultResourceLoader(this.getClass().getClassLoader()).
  24. getResource(configPath);
  25. PropertySource resourcePropertySource = new ResourcePropertySource(resource);
  26. return resourcePropertySource;
  27. }
  28. }
日志配置

Spring Boot 默认使用的是logback,在logback-spring.xml 的配置文件中可以使用Spring Profile,而且还有一个默认的CONSOLE Appender

</>复制代码

在没有使用Spring Boot的情况下,不能在logback的config中使用Spring Profile,只能分拆成多个文件,然后根据环境变量读取不同的配置文件,需要添加依赖org.logback-extensions

</>复制代码

  1. org.logback-extensions
  2. logback-ext-spring
  3. 0.1.4

logback-dev.xml

</>复制代码

  1. ${CONSOLE_LOG_PATTERN}
  2. utf8

logback-prod.xml

</>复制代码

  1. ${CONSOLE_LOG_PATTERN}
  2. utf8

下面的代码根据环境变量读取不同的配置文件

</>复制代码

  1. private static final String LOGCONFIG_PATH_PATTERN = "classpath:logback-%s.xml";
  2. public static void main(String[] args) throws FileNotFoundException, JoranException {
  3. String profile = System.getProperty("spring.profiles.active", "dev");
  4. System.setProperty("file.encoding", "utf-8");
  5. // logback config
  6. String logConfigPath = String.format(LOGCONFIG_PATH_PATTERN, profile);
  7. System.out.println("Using logback config: " + logConfigPath);
  8. LogbackConfigurer.initLogging(logConfigPath);
  9. SLF4JBridgeHandler.removeHandlersForRootLogger();
  10. SLF4JBridgeHandler.install();
  11. ConfigurableApplicationContext context = new CustomApplicationContext("classpath:applicationContext.xml");
  12. }
测试

有Spring Boot 的时候TestCase写起来很方便,在类上添加两行注解即可,在src est esources下的application.properties中设置spring.profiles.active=test即可指定Profile为test

</>复制代码

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class TestStockService {
  4. @Autowired
  5. StockService stockService;
  6. @Before
  7. public void setUp() {
  8. }
  9. @After
  10. public void tearDown() {
  11. }
  12. @Test
  13. public void testMissingBbTickerEN() {
  14. }
  15. }

不使用Spring Boot的情况下,需要指定好几个配置。

</>复制代码

  1. @RunWith(SpringRunner.class)
  2. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  3. @ActiveProfiles(profiles = "test")
  4. @TestPropertySource("classpath:application-test.properties")
  5. public class TestStockService {
  6. @Autowired
  7. StockService stockService;
  8. @Before
  9. public void setUp() {
  10. }
  11. @After
  12. public void tearDown() {
  13. }
  14. @Test
  15. public void testMissingBbTickerEN() {
  16. }
  17. }
打包

Spring Boot 会把项目和所依赖的 Jar 包打包成一个大 Jar 包,直接运行这个 Jar 包就可以。这个功能是通过spring-boot-maven-plugin实现的。

</>复制代码

  1. org.springframework.boot
  2. spring-boot-maven-plugin

不使用Spring Boot 之后,我们需要配置maven-jar-plugin,但是依赖包无法像Spring Boot一样打包成一个大的 Jar 包,需要我们指定classpath。

</>复制代码

  1. org.apache.maven.plugins
  2. maven-jar-plugin
  3. 2.6
  4. com.exmaple.demo.DemoApplication
  5. true
  6. lib/

注意:

当用java -jar yourJarExe.jar来运行一个经过打包的应用程序的时候,你会发现如何设置-classpath参数应用程序都找不到相应的第三方类,报ClassNotFound错误。实际上这是由于当使用-jar参数运行的时候,java VM会屏蔽所有的外部classpath,而只以本身yourJarExe.jar的内部class作为类的寻找范围。所以需要在jar包mainfest中添加classpath。

依赖包

使用下面的maven配置帮你把所有的依赖包复制到targetlib目录下,方便我们部署或者是测试时复制依赖包。

</>复制代码

  1. org.apache.maven.plugins
  2. maven-dependency-plugin
  3. copy-dependencies
  4. prepare-package
  5. copy-dependencies
  6. target/lib
  7. true
  8. junit,org.hamcrest,org.mockito,org.powermock,${project.groupId}
  9. true
  10. true
  11. ${project.build.directory}
运行

运行时通过指定命令行参数 -Dspring.profiles.active=prod 来切换profile

</>复制代码

  1. java -jar -Dspring.profiles.active=prod demo.jar
总结

Spring Boot很大程度上方便了我们的开发,但是隐藏了大量的细节,我们使用xml配置spring可以达到差不多同样的效果,但是在结构和配置上更加清晰。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68406.html

相关文章

  • SpringBoot简单入门

    摘要:接下来我们继续看如果达成包,在加入如下配置然后通过打包,最后通过命令启动这样,最简单的就完成了,但是对于一个大型项目,这是远远不够的,的详细操作可以参照官网。以上实例只是最简单的项目入门实例,后面会深入研究。 什么是Spring Boot Spring Boot是由Pivotal团队提供的基于Spring的全新框架,其设计目的是为了简化Spring应用的搭建和开发过程。该框架遵循约定大...

    BWrong 评论0 收藏0
  • SpringBoot基础入门篇

    摘要:基础入门篇简介可以基于轻松创建可以运行的独立的生产级的应用程序。对平台和第三方类库我们有自己看法和意见约定大于配置。官网目前最新版本是我们接下来就在这个版本的基础上面进行学习。变成项目引入依赖。 SpringBoot基础入门篇 简介 Spring Boot可以基于Spring轻松创建可以运行的、独立的、生产级的应用程序。 对Spring平台和第三方类库我们有自己看法和意见(约定大于配置...

    Edison 评论0 收藏0
  • Spring MVC+Stomp+Security+H2 Jetty

    摘要:在逐步开发过程中,发现自己需求,用户使用,页面样式,做得都不是很好。希望很和牛逼的人合作,一齐完善这个项目,能让它变成可以使用的产品。自己也可以在此不断学习,不断累计新的知识,慢慢变强起来。 showImg(https://segmentfault.com/img/bVboKz5);#### 这一个什么项目 ##### 使用技术 Spring MVC Spring Security ...

    gitmilk 评论0 收藏0
  • Spring Boot (一)helloworld

    摘要:第二个类级别注解是。将引导应用程序,启动,从而启动自动配置服务器。比如想使用不同版本的,具体如下在标签中还可以指定编译的版本和项目的编码格式指定项目编码为使用插件可以为项目提供的操作方式,的个,默认。 引言 Spring 框架对于很多 Java 开发人员来说都不陌生。Spring 框架包含几十个不同的子项目,涵盖应用开发的不同方面。如此多的子项目和组件,一方面方便了开发人员的使用,另外...

    go4it 评论0 收藏0
  • 一文掌握 Spring Boot Profiles

    摘要:需要注意的是必须要使用版本为以上才支持属性。与格式文件不同,正对不同的,无法在一个文件设置,官方采用命名形式为格式来达成一样的效果。采用方式添加的是属于额外激活的,也就是说覆盖掉外部传入的指定的。 showImg(https://segmentfault.com/img/remote/1460000019924197?w=1050&h=500); Spring Boot Profile...

    Eidesen 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<