Spring 3 provides a clean way to configure and use properties file to store placeholders. Let us assume that we have a properties file and want to use it’s properties in our spring config and java code.
Our placeholder.properties file looks like below
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/dms jdbc.username=root jdbc.password=secret document.root.path=c:\\docs
In my spring-servlet.xml config file i configure it like this
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:placeholder.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
autowire-candidate="true" autowire="byName">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
</beans>
Note the way i access my database configurations Now to access properties file using ${….} syntax.
Now in my Controller class i will be accessing the developer’s url mentioned in the properties file to render it on the UI.
@Controller
public class DocumentController {
private final Logger log = Logger.getLogger(this.getClass());
@Autowired
private DocumentService documentService;
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
@Value("${documents.root.path}")
private String documentRootPath;
/**
* Lists most recent documents
*
* @return
*/
@RequestMapping(value = "/docs", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listDocuments() {
String msg = "Recent Documents";
List<Metadata> lst = documentService.getRecentDocuments();
Long docCount = documentService.getAllDocumentCount(documentRootPath);
ModelAndView mav = new ModelAndView();
mav.setViewName("listDocs");
mav.addObject("msg", msg);
mav.addObject("lst", lst);
mav.addObject("docCount", docCount);
return mav;
}
}
In the code above note following snippet.
@Value("${documents.root.path}")
private String documentPath;
this is how you can access properties file values in your spring project’s java code.
#1 by sydney property valuer on November 25, 2012 - 7:17 pm
When someone writes an post he/she keeps the image of a user
in his/her mind that how a user can know it. Thus that’s why this article is great. Thanks!