资讯专栏INFORMATION COLUMN

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

eechen / 2978人阅读

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

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

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

Profile

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

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

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

public class CustomApplicationContext extends ClassPathXmlApplicationContext {

    public CustomApplicationContext(){
        super();
    }

    public CustomApplicationContext(String configLocation) {
        super(new String[]{configLocation}, true, null);
    }

    @Override
    public ConfigurableEnvironment createEnvironment() {
        return new CustomEnvironment();
    }
}
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.IOException;

public class CustomEnvironment extends StandardEnvironment {

    private static final String APPCONFIG_PATH_PATTERN = "classpath:application-%s.properties";

    @Override
    protected void customizePropertySources(MutablePropertySources propertySources) {
        super.customizePropertySources(propertySources);
        try {
            propertySources.addLast(initResourcePropertySourceLocator());
        } catch (IOException e) {
            logger.warn("failed to initialize application config environment", e);
        }
    }

    private PropertySource initResourcePropertySourceLocator() throws IOException {
        String profile = System.getProperty("spring.profiles.active", "dev");
        String configPath = String.format(APPCONFIG_PATH_PATTERN, profile);
        System.out.println("Using application config: " + configPath);

        Resource resource = new DefaultResourceLoader(this.getClass().getClassLoader()).
                getResource(configPath);
        PropertySource resourcePropertySource = new ResourcePropertySource(resource);
        return resourcePropertySource;
    }
}
日志配置

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





    
        
    


    
        
    

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


    org.logback-extensions
    logback-ext-spring
    0.1.4

logback-dev.xml



    
    
        
            ${CONSOLE_LOG_PATTERN}
            utf8
        
    
    
        
    

logback-prod.xml



    
    
        
            ${CONSOLE_LOG_PATTERN}
            utf8
        
    
    
        
    

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

    private static final String LOGCONFIG_PATH_PATTERN = "classpath:logback-%s.xml";

    public static void main(String[] args) throws FileNotFoundException, JoranException {
        String profile = System.getProperty("spring.profiles.active", "dev");
        System.setProperty("file.encoding", "utf-8");

        // logback config
        String logConfigPath = String.format(LOGCONFIG_PATH_PATTERN, profile);
        System.out.println("Using logback config: " + logConfigPath);
        LogbackConfigurer.initLogging(logConfigPath);
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
        
        ConfigurableApplicationContext context = new CustomApplicationContext("classpath:applicationContext.xml");
    }
测试

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestStockService {

    @Autowired
    StockService stockService;

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testMissingBbTickerEN() {

    }
}

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

@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@ActiveProfiles(profiles = "test")
@TestPropertySource("classpath:application-test.properties")
public class TestStockService {

    @Autowired
    StockService stockService;

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testMissingBbTickerEN() {
    }
}
打包

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


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

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


    org.apache.maven.plugins
    maven-jar-plugin
    2.6
    
        
            
                com.exmaple.demo.DemoApplication
                true
                lib/
            
        
    

注意:

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

依赖包

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


    org.apache.maven.plugins
    maven-dependency-plugin
    
        
            copy-dependencies
            prepare-package
            
                copy-dependencies
            
            
                target/lib
                true
                
                    junit,org.hamcrest,org.mockito,org.powermock,${project.groupId}
                
            
        
    
    
        true
        true
        ${project.build.directory}
    
运行

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

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元查看
<