当前位置: 首页 > 知识库问答 >
问题:

读取侦听器内的Spring Boot属性

孙熠彤
2023-03-14

我的需求是,当服务器在spring Boot中启动时,我需要初始化一些应用程序资源。为了初始化这些资源,我需要一些属性。因此,我将这些属性保存在外部属性文件中,并试图在Spring Boot启动时读取自定义侦听器中的属性。问题是,我无法在侦听器中获得任何属性值。我能够阅读后,申请开始没有任何问题。但是,当应用程序启动时,我需要它们在监听器内。我正在了解下面的异常...如何解决它。帮帮我!

    2015-08-20 02:58:59.585 ERROR 9376 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/shared]        : Exception sending context initialized ev
ent to listener instance of class com.org.man.api.initializer.PropertyInitializerListener

java.lang.NoSuchMethodError: com.org.man.api.beans.property.ConfigProperties.getConfigNames()Ljava/util/List;
        at com.org.man.api.beans.property.PropertyBeanParser.initializeConfigProperties(PropertyBeanParser.java:33)
        at com.org.man.api.initializer.J2eeInitializer.getJ2eePresets(J2eeInitializer.java:79)
        at com.org.man.api.initializer.J2eeInitializer.initialize(J2eeInitializer.java:36)
        at com.org.man.api.initializer.PropertyInitializerListener.contextInitialized(PropertyInitializerListener.java:81)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
        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)

2015-08-20 02:58:59.592 ERROR 9376 --- [ost-startStop-1] o.apache.catalina.core.StandardContext   : One or more listeners failed to start. F
ull details will be found in the appropriate container log file
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Fac
tory method 'viewControllerHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: The resources may not be ac
cessed if they are not currently started
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 23 common frames omitted
Caused by: java.lang.IllegalStateException: The resources may not be accessed if they are not currently started
        at org.apache.catalina.webresources.StandardRoot.validate(StandardRoot.java:245)
        at org.apache.catalina.webresources.StandardRoot.getResource(StandardRoot.java:212)
public class PropertyInitializerListener implements ServletContextListener {
private static final String INITIALIZED = PropertyInitializerListener.class.getName() + ".INITIALIZED";
private J2eeInitializer initializer;

@Autowired
PropertyBeanParser parser;

public void contextDestroyed(ServletContextEvent event) {
    if (initializer != null) {
        initializer.terminate();
    }

    ServletContext context = event.getServletContext();
    context.removeAttribute(FileSearcher.CONFIG_FILE_PROP);
}

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();

    if (context.getAttribute(INITIALIZED) != null) {
        throw new IllegalStateException(
            "Already initialized - " +
            "check whether you have multiple <listener> definitions in your web.xml!");
    }
    ConfigBean presets = super.getPresets();
    presets = parser.initializeConfigProperties();
    SmapiDebug.setSaveMode(true);
    SmapiDebug.info("contextInitialized");
@Configuration    

@EnableConfigurationProperties({ConfigProperties.class,LoggingProperties.class,
            InstrumentationProperties.class,KeyeventProperties.class})
        public class PropertyBeanParser {

            @Autowired
            private ConfigProperties configProperties;

            @Autowired
            private LoggingProperties loggingProperties;

            @Autowired
            private InstrumentationProperties instrumentationProperties;

            @Autowired
            private KeyeventProperties keyeventProperties;

            public ConfigBean initializeConfigProperties(){

                ConfigBean configBean = new ConfigBean();
                try{
                    if(configProperties.getConfigNames()!=null && configProperties.getConfigValues()!=null) {
                        if(configProperties.getConfigNames().size()==configProperties.getConfigValues().size()){
                            for(int i=0;i<=configProperties.getConfigNames().size();i++){
                                ConfigVarDefinitionBean var = new ConfigVarDefinitionBean(configProperties.getConfigNames().get(i),
                                        configProperties.getConfigValues().get(i));
                                configBean.addConfigVarDefinition(var);
                            }
                        }
                        else{
                            throw new Exception("number of names and values are not matching");
                        }
                    }

                }
                catch(Exception e){
                    e.getMessage();
                }
                return configBean;
            }
        }
@Configuration
@ConfigurationProperties(locations = "file:config.properties", prefix = "config")
public class ConfigProperties {

    private List<String> configNames = new ArrayList<String>();
    private List<String> configValues = new ArrayList<String>();
    public List<String> getConfigNames() {
        return configNames;
    }
    public void setConfigNames(List<String> configNames) {
        this.configNames = configNames;
    }
    public List<String> getConfigValues() {
        return configValues;
    }
    public void setConfigValues(List<String> configValues) {
        this.configValues = configValues;
    }
}

config.properties

config.configNames[0]=test1
config.configNames[1]=Testserver
config.configNames[2]=ResourceId
config.configNames[3]=AdaptorName
config.configNames[4]=runLevel

config.configValues[0]=ServiceComp
config.configValues[1]=Test
config.configValues[2]=instance2
config.configValues[3]=test
config.configValues[4]=localhost

共有1个答案

仲孙钊
2023-03-14

问题是,在Spring Boot启动期间,无法在侦听器内检索属性。因此,为了在启动过程中进行一些初始化,我们可以通过实现CommandLineRunner在设置@SpringBootApplication注释的类中添加run方法。如果这样做,那么运行方法将在完成SpringApplication的运行方法之前执行。

@SpringBootApplication
public class SpringResource implements CommandLineRunner {

    /**
     * @param args
     */
    @Autowired
    PropertyTest test;

    public void run(String... args){
        test.print();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringResource.class, args);

    }
}

PropertyTest类

@Configuration
@EnableConfigurationProperties({ConfigProperties.class})
@Controller
public class PropertyTest {

    @Autowired
    ConfigProperties config;


    @RequestMapping(value = "/dummy", method = RequestMethod.GET)
    @ResponseBody
    public void print() {
        // TODO Auto-generated method stub
        for(int i=0;i<config.getConfigNames().size();i++)
        System.out.println("Im in Property test method. :)" +config.getConfigNames().get(i)+" "+config.getConfigValues().get(i));
    }

}
 类似资料:
  • 如果我向JavaFx属性添加onChange侦听器, 监听器是按顺序调用的吗?如果我有一个字符串属性,然后我把字符串转到“爱丽丝”,然后转到“鲍勃”,我保证在看到“鲍勃”之前看到“爱丽丝”吗?事实上,我不在乎我是否看到“爱丽丝”,只要我看不到“鲍勃”之后 监听器是按顺序调用的吗?我的监听器有可能同时被“爱丽丝”和“鲍勃”通知调用吗?

  • 问题内容: 有人知道在python中跟踪字典对象更改的任何简便方法吗?我的工作水平很高,所以我有一些方法可以处理更改字典的操作,如果字典发生更改,我想调用一个函数来基本上执行Observer / Notify。 我要避免的是所有跟踪(设置布尔值)代码。希望有一种更轻松的方式来跟踪更改。这是一个简单的情况,但是可能存在更复杂的逻辑,这将导致我不得不设置更改的标志。 问题答案: 您可以从该类派生并在任

  • 问题内容: 我当时在上网,但找不到很好的信息。我试图在每次运行应用程序时检测按键。我正在使用JavaFX并将其与FXML一起运行。我尝试了很多事情,但没有任何效果。请帮我。 问题答案: 您应该签出Ensemble示例。这是关键的侦听器代码。

  • 我正在使用Realex Payments的HPP API开发一个卡支付页面,其中包含一个iFrame,用于托管Realex页面。在Realex请求表单上,我将字段HPP_POST_维度和HPP_POST_响应设置为我的URL,如下所示: 付款页: www.example.com/account/payment.html 隐藏字段值用于在HPP页面大小更改和事务完成时,使用事件侦听器将数据从Real

  • 虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的侦听器。这就是为什么 Vue 通过watch选项提供了一个更通用的方法,来响应数据的变化。当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。例如: <div id="watch-example"> <p> Ask a yes/no question: <input v-model="question">

  • 1. 前言 本节介绍侦听器 watch 的使用方法。包括什么是侦听器,侦听器的特点,以及如何对不同类型的数据进行监听。其中重点掌握对不同类型的数据如何使用侦听器,了解它之后,在才能在之后的日常开发中熟练运用。 2. 慕课解释 Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属性。 — 官方定义 侦听器 watch 是 Vue 提供的一种用来观察和响应 Vue 实例上的数据