简体   繁体   中英

Order of component scanning in spring

Am new to spring, had defined the ApplicaionConfig.java there I placed the property file details.

package com.rao.first;

//
//  import statements
//

@Configuration
@ComponentScan(basePackageClasses = { ApplicationConfig.class  }, basePackages = { "com.rao.first" })
@PropertySources({ 
@PropertySource("file:${webapp.root}/resources/config/application.properties"),
@PropertySource(value = "file:${conf.dir}/someother.properties", ignoreResourceNotFound = true) })
class ApplicationConfig
{
    @Bean
    ServletContextListener logbackConfigListener()
    {
        return new LogbackConfigListener();

    }
}

and defined some controller classes.

package com.rao.first.controller;
//
//  import statements
//
@Controller
@RequestMapping(value = "/first")
public class FirstController
{
    private String viewerUrl;

    @Inject
    public FirstController(Environment env)
    {
        this.viewerUrl = env.getProperty("property1");
    }

    //
    //

}

But here first controller is executing, after that ApplicaitonConfig is executing, so unable to get the data from property file.

And spring-servlet.xml file configurations are

<context:component-scan base-package="com.rao.first.view" />
<context:component-scan base-package="com.rao.controller.security" />
<context:component-scan base-package="com.rao.controller" />

Please guide me how can set order of execution?

You could use org.springframework.context.annotation.PropertySource annotation to retrieve values from a properties file.

So your controller class could be like following:

package com.rao.first.controller;
import org.springframework.context.annotation.PropertySource;
//
//  import statements
//
@Controller
@RequestMapping(value = "/first")
@PropertySource("classpath:/com/rao/app.properties")
public class FirstController
{
    private String viewerUrl;

    @Autowired
    Environment env;

    public FirstController()
    {
        this.viewerUrl = env.getProperty("property1");
    }

    //
    //

}

I hope it helps you, bye.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM