membersound
membersound

Reputation: 86935

How to import properties file within shared jar in Spring?

I'd like to create a shared project jar, that has some services. These service should make use of a properties file.

Ideally I just want to make use of the services lateron when I add the shared jar as a dependency to other projects. I don't want to make any further configuration like importing the shared property file or so.

Within the shared jar, I'd like to inject the properties using Spring. But how can I do this?

project-commons/src/main/java:

@Service
public class MyService {
    @Value("${property.value}") private String value;

    public String getValue() {
        return value;
    }
}

project-commons/src/main/resources/application.properties:

property.value=test

project-web/src/main/java:

@Component
public class SoapService {
    @Autowired
    private MyService service;

    //should return "test"
    public String value() {
        return service.getValue();
    }
}

When I run it:

Illegal character in path at index 1: ${property.value}

So, the propertyfile is not resolved. But how can I tell spring to automatically use it when using the appropriate service?

Upvotes: 5

Views: 5149

Answers (2)

membersound
membersound

Reputation: 86935

Thanks to the comment of Hank Lapidez, adding the following statement fixes the problem:

@Configuration
@PropertySource("classpath:appdefault.properties")
public CommonConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

Upvotes: 3

Software Engineer
Software Engineer

Reputation: 16140

You need to have some variation of this:

    <context:property-placeholder location="classpath:my.properties" ignore-unresolvable="true"/>

in your application context xml file, or the equivalent in a java configurator (see @PropertySource("classpath:my.properties")). This should be repeated in any module that depends on the shared library's property file.

Upvotes: 1

Related Questions