I am very new to spring mvc 3 annotation based application. I have two properties files - WEB-INF\resources\general.properties, WEB-INF\resources\jdbc_config.properties
Now I want to configure them through spring-servlet.xml. How I can achieve this?
In general.properties,
label.username = User Name:
label.password = Password:
label.address = Address:
...etc jdbc_config.properties,
app.jdbc.driverClassName=com.mysql.jdbc.Driver
app.jdbc.url=jdbc:mysql://localhost:[port_number]/
app.jdbc.username=root
app.jdbc.password=pass
---etc
If I want to get label.username and app.jdbc.driverClassName in my jsp page, how do I code for them?
I also want to access these properties values from my service. How to get these property values using respective keys in method level in service class or controller class?
You need to distinguish between application properties (configuration) and localisation messages. Both use JAVA properties files, but they serve different purpose and are handled differently.
Note: I am using Java based Spring configuration in the examples bellow. The configuration can be easily made in XML as well. Just check Spring's JavaDoc and reference documentation.
Application Properties
Application properties should be loaded as property sources within your application context. This can be done via @PropertySource
annotation on your @Configuration
class:
@Configuration
@PropertySource("classpath:default-config.properties")
public class MyConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Then you can inject properties using @Value
annotation:
@Value("${my.config.property}")
private String myProperty;
Localisation Messages
Localisation messages is a little bit different story. Messages are loaded as resource bundles and a special resolution process is in place for getting correct translation message for a specified locale.
In Spring, these messages are handled by MessageSource
s. You can define your own for example via ReloadableResourceBundleMessageSource
:
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/messages/messages");
return messageSource;
}
You can access these messages from beans if you let Spring inject MessageSource
:
@Autowired
private MessageSource messageSource;
public void myMethod() {
messageSource.getMessage("my.translation.code", null, LocaleContextHolder.getLocale());
}
And you can translate messages in your JSPs by using <spring:message>
tag:
<spring:message code="my.translation.code" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With