2014-07-21 128 views
2

我想创建一个共享项目jar,它有一些服务。这些服务应该使用属性文件。如何在Spring中的共享jar中导入属性文件?

理想情况下,我只是想在将共享jar作为依赖项添加到其他项目时使用这些服务。我不想进行任何进一步的配置,如导入共享属性文件等。

在共享jar中,我想使用Spring注入属性。但我该怎么做?

项目的公共/ src目录/主/ java的:

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

    public String getValue() { 
     return value; 
    } 
} 

项目的公共/ src目录/主/资源/ application.properties:

property.value=test 

项目的web/src目录/主/ Java的:

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

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

当我运行它:

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

因此,propertyfile没有解析。但是如何告诉spring在使用适当的服务时自动使用它?

+1

你有一个配置文件加载的属性? –

+2

这是一个很好的博客文章:http://www.baeldung.com/2012/02/06/properties-with-spring/#java –

+0

不,我应该吗?在另一个项目中注入此服务时,我宁愿不必配置任何东西。 – membersound

回答

1

感谢汉克Lapidez的评论,添加以下语句解决了这个问题:

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

你需要有这样一些变化:

<context:property-placeholder location="classpath:my.properties" ignore-unresolvable="true"/> 
在您的应用程序上下文XML文件

,或者在Java配置等效(见@PropertySource("classpath:my.properties"))。这应该在任何取决于共享库的属性文件的模块中重复。

相关问题