草庐IT

java - Spring Boot YML 和 StandAlone Tomcat 8 服务器

coder 2024-03-20 原文

我有以下目录结构/配置文件:

src/main/resource/config: 
application.yml 
application-dev.yml 
application-sit.yml

注意根据“Bootiful Configurationhttps://spring.io/blog/2015/01/13/configuring-it-all-out-or-12-factor-app-style-configuration-with-spring :

Spring Boot will read the properties in src/main/resources/application.properties by default. If a profile is active, it will also automatically reads in the configuration files based on the profile name, like src/main/resources/application-foo.properties where foo is the current profile. If the Snake YML library is on the classpath, then it will also automatically load YML files.

如果我将 --spring.profiles.active=dev 设置为 snake YML jar 在类路径中 在 eclipse 运行配置中编程 arg 并将其用作我的主要方法一切都按预期工作:

  public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);

        SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);

        // Check if the selected profile has been set as argument.
        // if not the development profile will be added
        addDefaultProfile(app, source);

        app.run(args);
    }

    /**
     * Set a default profile if it has not been set
     */
    private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
        if (!source.containsProperty("spring.profiles.active")) {
            app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
        }
    }

(请注意上面的主要方法引用来 self 的代码中使用的以下类:https://github.com/jarias/generator-jhipster-ember/blob/master/app/templates/src/main/java/package/_Application.java)

对于 spring.profile.active=dev,一切都按预期工作。这意味着两者: application.yml(默认加载)和application-dev.yml( Activity 配置文件)属性文件被加载并排除 application- sit.yml 因为 sit 不是一个活跃的个人资料。

这个嵌入式容器非常适合开发测试。但是,我想通过生成 war 并将其部署到独立的 Tomcat8 服务器来将其发布到生产环境中。

为此,我创建了 WebApplicationInitializer 的实现,Tomcat8 服务器需要它来自动检测、引导和启动独立服务器上的 spring 应用程序。

@Configuration
public class WebAppInit implements WebApplicationInitializer {


    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        }
}

部署 war 后我收到以下错误我尝试启动独立服务器并收到以下错误:

Caused by: org.springframework.beans.factory.enter code hereBeanCreationException: Could not autowire field: private java.lang.String com.titlefeed.config.db.DbConfigJPA.databaseUrl; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder spring.data.postgres.uri' in string value "${spring.data.postgres.uri}"

这意味着 Tomcat Server/Spring isnt 加载 application-dev.yml 因为它包含以下属性:spring.data.postgres.uri

所以我尝试了以下两种解决方案

  1. 添加-Dspring.profiles.active=dev到tomcat/bin/catalina.sh中的JAVA_OPTS
  2. 添加 spring.profiles.active=dev 到 tomcat/conf/catalina.properties

而且他们都没有工作。如何让独立的 tomcat 服务器加载与 spring.profiles.active 属性关联的 yml 文件。

它适用于从 eclipse 启动的嵌入式 springboot 服务器,但不适用于独立服务器?

EDIT1:M. Deinum - 实现了您在下面建议的解决方案,但仍然出现以下错误:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.data.postgres.uri' in string value "${spring.data.postgres.uri}

似乎没有设置 -Dspring.profiles.active=dev。

@Configuration
public class WebAppInit extends SpringBootServletInitializer {

 @Override

    protected WebApplicationContext createRootApplicationContext(
            ServletContext servletContext) {
           log.info("Properly INITALIZE spring CONTEXT");
           ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
           servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
           return super.createRootApplicationContext(servletContext);
    }

}

编辑 2 ACV: - 在启动脚本中添加“--spring.profiles.active=dev”作为 JAVA_OPTS 变量的一部分:tomcat/bin/catalina.sh 不是一个可行的选项

例如:

 JAVA_OPTS="$JAVA_OPTS --spring.profiles.active=dev ...etc

出现以下错误:

Unrecognized option: --spring.profiles.active=dev Error: Could not create the Java Virtual Machine."

编辑 3: 修改了 application.yml 以包含以下属性

spring:
  profiles:
    active: dev

重新部署 war 。转到展开的 tomcat 目录位置以确保属性存在 webapps/feedserver/WEB-INF/classes/config/application.yml

问题依旧。

编辑 4: 在 tomcat exploded webdir 下添加了 application.properties:webapps/feedserver/WEB-INF/classes/application.properties:

spring.profiles.active=dev
spring.data.postgres.uri=jdbc:postgresql://localhost:5432/feedserver

重启tomcat,问题依旧。

它似乎没有获取 application.propertiesapplication.yml

编辑 5 使用推荐的方式为外部容器启动 spring boot 服务器:

@Configuration
public class WebAppInit extends SpringBootServletInitializer {

 @Override
 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
     return application.sources(Application.class);
 }

}

编辑 6:

我在启动命令参数中添加了-Dspring.profiles.active=dev:

/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/bin/java -Djava.util.logging.config.file=/Users/shivamsinha/Desktop/Programming/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Dlog4j.rootLevel=ERROR -Dlog4j.rootAppender=console -DENV=dev -Dlog4j.configuration=/WEB-INF/classes/properties/log4j.properties -DTOMCAT_DIR=WEB-INF/classes/ -Djava.endorsed.dirs=/Users/shivamsinha/Desktop/Programming/tomcat/endorsed -classpath /Users/shivamsinha/Desktop/Programming/tomcat/bin/bootstrap.jar:/Users/shivamsinha/Desktop/Programming/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/Users/shivamsinha/Desktop/Programming/tomcat -Dcatalina.home=/Users/shivamsinha/Desktop/Programming/tomcat -Djava.io.tmpdir=/Users/shivamsinha/Desktop/Programming/tomcat/temp org.apache.catalina.startup.Bootstrap -Dspring.profiles.active=dev start

但是我仍然在日志中得到以下异常:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String com.titlefeed.config.db.DbConfigJPA.databaseUrl; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.data.postgres.uri' in string value "${spring.data.postgres.uri}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 68 more
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.data.postgres.uri' in string value "${spring.data.postgres.uri}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:801)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:955)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
    ... 70 more

02-Sep-2015 03:15:40.472 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive /Users/shivamsinha/Desktop/Programming/tomcat/webapps/feedserver-1.0.0.war
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/feedserver-1.0.0]]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:728)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:917)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1701)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

最佳答案

来源:@M。 Deinum

将 spring profile args 传递到 Tomcat 8 有两种选择。

1.设置为环境变量

Tomcat 允许您在启动过程中调用的 CATALINA_HOME/setenv.shCATALINA_BASE/setenv.sh 中设置环境配置。

setenv.sh:
export SPRING_PROFILES_ACTIVE=dev

您可能还想创建一个包含以下行的 src/main/resources/banner.txt:

active profiles     :: ${spring.profiles.active}

它不会在您的 IDE 中工作(它从您的 jar/war 的 MANIFEST.MF 文件中读取,如果您正常编译则不会有),但在您关心的环境中它真的很方便 --除了您的本地环境之外的一切!

2.将其添加到执行类之前的启动脚本/命令中

我修改了 CATALINA_HOME/catalina.sh 添加了一个声明的变量:

SPRING_PROFILE="dev"

并且在所有相关执行中将其添加到脚本中:

  eval "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
      -Djava.endorsed.dirs="\"$JAVA_ENDORSED_DIRS\"" -classpath "\"$CLASSPATH\"" \
      -Dcatalina.base="\"$CATALINA_BASE\"" \
      -Dcatalina.home="\"$CATALINA_HOME\"" \
      -Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
      -Dspring.profiles.active="\"$SPRING_PROFILE\"" \
      org.apache.catalina.startup.Bootstrap "$@" start \
      >> "$CATALINA_OUT" 2>&1 "&"

显然这不是推荐的方法。但它有效!如果您确实有执行此操作的完全可复制的步骤,建议的方法可以随时发布答案,如果有效,我会接受。

关于java - Spring Boot YML 和 StandAlone Tomcat 8 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32327522/

有关java - Spring Boot YML 和 StandAlone Tomcat 8 服务器的更多相关文章

  1. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  4. ruby-on-rails - 启动 Rails 服务器时 ImageMagick 的警告 - 2

    最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru

  5. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  6. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

  7. ruby-on-rails - 在 Rails 中调试生产服务器 - 2

    您如何在Rails中的实时服务器上进行有效调试,无论是在测试版/生产服务器上?我试过直接在服务器上修改文件,然后重启应用,但是修改好像没有生效,或者需要很长时间(缓存?)我也试过在本地做“脚本/服务器生产”,但是那很慢另一种选择是编码和部署,但效率很低。有人对他们如何有效地做到这一点有任何见解吗? 最佳答案 我会回答你的问题,即使我不同意这种热修补服务器代码的方式:)首先,你真的确定你已经重启了服务器吗?您可以通过跟踪日志文件来检查它。您更改的代码显示的View可能会被缓存。缓存页面位于tmp/cache文件夹下。您可以尝试手动删除

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  10. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

随机推荐