Spring 4.1.6 - Load ".properties" and initialize a bean with that - java

I'm new with Spring MVC and I'm doing some tests. I was trying to find some answers about this issues, but most of them make references to Spring 3.11 and I'm using the last release: 4.1.6.
I want to load a ".properties" file when the application starts, and use the information in it to create a bean to access it in all the context of the app.
So far, I reach to load the file in the servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
...
<context:property-placeholder location="classpath*:resources/Resources.properties" />
</beans:beans>
I think (not really sure) that I correctly declared the bean in the root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="Resources" class="ar.com.violenciaesmentir.blog.resources.ResourcesDB"/>
</beans>
And I also think I made the bean correctly, but I don't really know if the annotations are right:
package ar.com.violenciaesmentir.blog.resources;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
#Service
public class ResourcesDB {
#Value("DB.NAME")
private String name;
#Value("DB.TYPE")
private String type;
#Value("DB.USER")
private String user;
#Value("DB.PASS")
private String pass;
#Value("DB.DRIVER")
private String driver;
#Value("DB.URL")
private String url;
#Value("DB.MAXACTIVE")
private String maxActive;
#Value("DB.MAXIDLE")
private String maxIdle;
#Value("DB.MAXWAIT")
private String maxWait;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMaxActive() {
return maxActive;
}
public void setMaxActive(String maxActive) {
this.maxActive = maxActive;
}
public String getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(String maxIdle) {
this.maxIdle = maxIdle;
}
public String getMaxWait() {
return maxWait;
}
public void setMaxWait(String maxWait) {
this.maxWait = maxWait;
}
}
My ".properties" file:
DB.NAME = jdbc/Blog
DB.TYPE = javax.sql.DataSource
DB.USER = blog
DB.PASS = blog
DB.DRIVER = oracle.jdbc.driver.OracleDriver
DB.URL = jdbc:oracle:thin:#localhost:1521:xe
DB.MAXACTIVE = 20
DB.MAXIDLE = 5
DB.MAXWAIT = 10000
I think the reference is ok because it gave me troubles when starting the server, saying that it couldn't find the property for "name", but I was doing the annotation wrong and then I fixed.
What I want is to have that bean initialized and be avaible to have an attribute in the DB class like:
#ManagedAttribute
private ResourcesDB resources;
...
public void foo() {
String dbName = resources.getName();
}
When I try it, resources is null. What I'm doing wrong?
-----UPDATE-----
Ok, I could solve the problem doing some try&fail with the answers given. First of all, I corrected the #Value like ("${DB.NAME}") and added a value to the service annotation #Service(value="Resources").
Then, the only change I got to do was in the servlet-context.xml. Instead of:
<context:property-placeholder location="classpath*:resources/Resources.properties" />
I used:
<beans:bean id="configuracion" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<beans:property name="location" value="classpath:Resources.properties"/>
</beans:bean>
And used #Autowire instead of #ManagedBean to access the bean.

There are 2 things flawed in your code.
Your #Value expressions are wrong
Your <context:property-placeholder /> must be in the same context as the beans
When using #Value you have to use placeholders, by default ${property name} you are just using a name. So update your annotations to reflect that. I.e. #Value("${DB.NAME}.
Next you have defined <context:property-placeholder /> in the context loaded by the DispatcherServlet whereas your beans are loaded by the ContextLoaderListener. The property placeholder bean is a BeanFactoryPostProcessor and it will only operate on bean definitions loaded in the same context. Basically your bean definition are in the parent context and your placeholder in the child context.
To fix move <context:property-placeholder /> to the same context where you bean is defined in.
Instead of #ManagedAttribute which is a JSF annotation use #Autowired or #Inject. And if you don't have a <context:component-scan /> add a <context:annotation-driven />.

Your #Value syntax is incorrect. It should be #Value("${DB.NAME}").
You might also need to add this to your XML config:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:resources/Resources.properties" />
</bean>
The value on the location may vary, not sure on how you are structuring and building your artifacts.

Related

'javax.servlet.ServletContext' that could not be found

I have a Springboot application as follows:
#SpringBootApplication
#ImportResource("classpath:/config/applicationContext.xml")
public class TaxBatchMain {
#Autowired
TaxIdService taxIdService;
private static final Logger LOGGER = LogManager.getLogger(TaxBatchMain.class);
public static void main(String[] args) {
new SpringApplicationBuilder(TaxBatchMain.class).web(false).run(args);
TaxBatchMain taxBatchMain = new TaxBatchMain();
}
public TaxBatchMain() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
#PostConstruct
public void checkForTransactions() {
try {
////
String tab = "someother content";
String footer = taxIdService.formatFooter();
////
////
}catch(){
//////////
}
}
}
TaxIdServiceImpl class is as follows:
#Service
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TaxIdServiceImpl implements TaxIdService {
#Autowired
private ServletContext servletContext;
private String formatFooter(String footer) {
String[] searchList = {"<ENVIRONMENT_NAME>", "<MS_ENV_NAME>"};
String[] replacementList = {(String) servletContext.getAttribute(ServletContextKey.EMAIL_HOST_NAME.name()),
(String) servletContext.getAttribute(ServletContextKey.MS_EMAIL_HOST_NAME.name())};
return StringUtils.replaceEach(footer, searchList, replacementList);
}
}
Application Context looks like:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"....................///
<context:annotation-config />
<context:property-placeholder location="classpath:/config.properties" />
<util:properties id="configProperties" location="classpath:/config.properties" />
<!-- <context:property-placeholder location="classpath:data/application.properties"/> -->
<context:component-scan base-package="com.tax.main" />
<context:component-scan base-package="com.tax.service" />
<context:component-scan base-package="com.tax.model" />
<context:component-scan base-package="com.tax.mapper" />
<context:component-scan base-package="com.tax.util" />
/////
When I run the main class i get foll. error
APPLICATION FAILED TO START
Description:
Field servletContext in com.tax.service.TaxIdServiceImpl required a bean of type 'javax.servlet.ServletContext' that could not be found.
Action:
Consider defining a bean of type 'javax.servlet.ServletContext' in your configuration.
Try enabling webEnvironment. It appears your SpringApplicationBuilder is not enabled with web environment.
new SpringApplicationBuilder(TaxBatchMain.class).web(true).run(args);
Since you are using spring-boot you can consider using Annotation based approach rather xml based.

How to use #Value on Spring non-managed class

Here my (simplified) code before explaining my problem :
foo.bar.MyFile
public class MyFile extends MyFileAbstract {
#Value("${FILE_PATH}")
private String path;
[...]
public MyFile(final Date date, final String number, final List<MyElement> elements) {
this.date = date;
this.number = number;
this.elements = elements;
}
#Override
public String getPath() {
return path;
}
[...]
}
foo.bar.MyService
#Service
public class MyService {
[...]
public String createFolder(MyFileAbstract file) throws TechnicalException {
[...]
String path = file.getPath();
[...]
}
[...]
}
the call of service
[...]
#Autowired
MyService service;
public void MyMethod() {
MyFile file = new MyFile();
service.createFolder(file);
[...]
}
[...]
I use a context XML to configure Spring :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<context:property-placeholder
file-encoding="utf-8"
location="file:///[...]/MyProperties.properties" />
<context:annotation-config />
<context:component-scan base-package="foo.bar.classes" />
[...]
</beans>
The problem is that the variable path is null at runtime in both MyService and MyFile file when a instantiate MyFile to call my service MyService.
I am looking a solution to inject my property ${FILE_PATH} inside MyFile.
Here my environment :
Apache Tomcat 7
Java 8
Spring 4.1.6.RELEASE
I have seen that Spring AOP with #Configurable bean could resolve this but don't want to change my Java Agent because I don't want to modify the configuration on the production server.
And I don't know how to use #Service on MyFile with my custom constructor.
Any idea is welcome.
You can add to your MyService
#Autowired
private Environment environment;
and just get the value
environment.getProperty("FILE_PATH");
After that you can set it to the file if necessary.
#Service
public class BeanUtilityService implements ApplicationContextAware {
#Autowired
private static ApplicationContext context;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
Create a Utility class as a service , create a static method and get the bean from the context.Then use that bean to get the properties required
use #PropertySource annotation
#PropertySource("classpath:config.properties") //use your property file name
public class MyFile extends MyFileAbstract {
#Value("${FILE_PATH}")
private String path;
[...]
public MyFile(final Date date, final String number, final List<MyElement> elements) {
this.date = date;
this.number = number;
this.elements = elements;
}
#Override
public String getPath() {
return path;
}
[...]
}

Spring Autowiring when using Configuration Class

I have a xml bean file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:annotation-config/>
<bean id="helloWorld" class="com.a.b.HelloWorld">
<property name="attr1" value="Attr1 from XML"></property>
</bean>
<bean id="helloWorld2" class="com.a.b.HelloWorld2">
<property name="attr2" value="Attr2 from XML"></property>
</bean>
</beans>
And I have use constructor autowiring like this
public class HelloWorld2{
private String attr2;
public void setAttr2(String message){
this.attr2 = message;
}
public void getAttr2(){
System.out.println("getAttr2 == " + attr2);
}
}
public class HelloWorld{
private String attr1;
private HelloWorld2 helloWorld2;
public HelloWorld(){
}
#Autowired
public HelloWorld(HelloWorld2 helloWorld2){
System.out.println("hhh");
this.helloWorld2 = helloWorld2;
}
public void setAttr1(String message){
this.attr1 = message;
}
public void getAttr1(){
System.out.println("getAttr1 == " + attr1);
}
public void getH(){
helloWorld2.getAttr2();
}
}
And autowiring is working fine.
Now I want to move my beans to Configuation class.
But then how to move the code so as autowiring works?
I have tried like this, but its not working
#Configuration
public class Config {
#Bean
public HelloWorld helloWorld(){
HelloWorld a = new HelloWorld();
a.setAttr1("Demo Attr1");
return a;
}
#Bean
public HelloWorld2 helloWorld2(){
HelloWorld2 a = new HelloWorld2();
a.setAttr2("Demo Attr2");
return a;
}
}
I think what you want to achieve is the injection of a HelloWorld2 instance into the method that creates the HelloWorld #Bean?
This should do it:
#Configuration
public class Config {
#Bean
public HelloWorld helloWorld(HelloWorld2 helloWorld2){
HelloWorld a = new HelloWorld(helloWorld2);
a.setAttr1("Demo Attr1");
return a;
}
#Bean
public HelloWorld2 helloWorld2(){
HelloWorld2 a = new HelloWorld2();
a.setAttr2("Demo Attr2");
return a;
}
}
This might be a duplication of these questions:
Understanding Spring Autowired usage
Converting Spring XML file to Spring configuration class

In Spring, annotation and xml must be used together?

A class
public class A {
private String name;
public A() {
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
BeanFactory class
public class BeanFactory implements InitializingBean, DisposableBean{
private A a;
public BeanFactory(){
}
public BeanFactory(A a){
this.a = a;
}
public void printAName(){
System.out.println("Class BeanFactory: beanFactory.printAName -> a.getName() = " + a.getName());
}
}
Main
public class Main {
public static void main(String[] args) {
AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"ApplicationContext.xml");
BeanFactory beanFactory = applicationContext.getBean("beanFactory",
BeanFactory.class);
beanFactory.printAName();
}
}
ApplicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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">
<context:annotation-config />
<bean id="beanFactory" class="testSpring.BeanFactory">
<constructor-arg ref="a1"/>
</bean>
<bean id="a1" class="testSpring.A">
<property name="name" value="I am A!"></property>
</bean>
</beans>
Result of run: Class BeanFactory: beanFactory.printAName -> a.getName() = I am A!
Like you can see, here I don't use no annotation. But the code works thanks to xml file.
So xml doesn't need annotation..? Can I use one or the other?
If I would use, in this application, the annotation (#Autowired for example) instead of bean xml, it's possible? Can you show me how?
Or the annotation must require xml reference?
So.. annotation and xml must be used together? Thanks
You should use annotation configuration, this is the idea
#Component
class Bean1 {
public Bean1() {
System.out.println(getClass());
}
}
#Configuration
#ComponentScan("test")
public class Config {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
}
}
For details see Spring docs

Unit testing with mongodb repositories

I have built application that uses MongoDB and I have came across problem with testing.
As long as I used JPA and some relational database I used some test layer which switched persistence to in-memory database (linke HSQLDB or MySQL) for test purposes. This way I was able to limit IO operations and speed up tests.
However with MongoDB and Spring Data it is very convenient to use repositories based on interfaces extending MongoRepository.
My question is how to deal with unit testing and functional testing when using repositories? For example I have simple class that is anotated as mongo document:
public class Company {
#Id
private String id;
#NotEmpty
private String name;
private String description;
private String website;
private String logo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
}
and related repository:
#Repository
public interface CompanyRepository extends MongoRepository<Company, Serializable> {
}
It is used in coresponding controller:
#RestController
public class CompanyController {
private static final Logger log = LoggerFactory.getLogger(CompanyController.class);
#Autowired
private CompanyRepository repository;
#RequestMapping(value = "/company", method = RequestMethod.POST)
public void create(#Valid #RequestBody(required = true) Company company) {
repository.save(company);
}
}
Finally I made two tests (however it could be one covering both tasks) that covers controller api and data format (where I mock repository to prevent from IO operations, and it works nice), and second where I want to make sure that passed object was persisted successfuly. As it cames out it is not so simple. First of all (correct me if I'm wrong) there is no in-memory mongo implementation. Secondly, I cannot verify with mockito execution of save method because of inheritance I suppose.
#ContextConfiguration(classes = Application.class)
#WebAppConfiguration
public class CompanyControllerNGTest extends AbstractTestNGSpringContextTests {
#Mock
private CompanyRepository repositoryMock;
#Autowired
#InjectMocks
private CompanyController controller;
private MockMvc mockMvc;
#BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#DataProvider
public static Object[][] companyJsonProvider() {
return new Object[][]{
{Json.createObjectBuilder()
.add("name", "JakasFirma")
.add("description", "jakas firma opis")
.add("website", "www.jakasfirma.com")
.add("logo", "jakies logo")
.build(), status().isOk()},
{Json.createObjectBuilder()
.add("name", "JakasFirma")
.build(), status().isOk()},
{Json.createObjectBuilder()
.add("description", "jakas firma opis")
.add("website", "www.jakasfirma.com")
.add("logo", "jakies logo")
.build(), status().isBadRequest()},
{Json.createObjectBuilder()
.build(), status().isBadRequest()},
};
}
#Test(dataProvider = "companyJsonProvider", enabled = false)
public void apiTest(JsonObject companyJson, ResultMatcher expectedStatus) throws Exception {
//given
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
String content = companyJson.toString();
//when
mockMvc.perform(post("/company").contentType(MediaType.APPLICATION_JSON).content(content)).
//then
andExpect(expectedStatus);
}
#Test
public void shouldCreate() throws Exception {
//given
//when
controller.create(mock(Company.class));
//then
//verify(repositoryMock, times(1)).save(any(Iterable.class));
}
}
I thought about introducing a dao layer between controller and repository that could be mocked and verified bot it adds more complexity and force to encapsulate each method used by repository. Also it doesn't fix problem but partially moves it to lower level.
Is there any method or practice that could help to deal with this kind of problem? Or maybe I should use different approach with mongo?
For unit testing I would stub or write an implementation of CompanyRepository and inject that into your controller (you may need to add a Setter method for CompanyRepository).
For Functional or integration testing I would look at using the following
#ContextConfiguration("file:my-context-file.xml")
#RunWith(SpringJUnit4ClassRunner.class)
In the context file I would expect you to configure the beans that are only required for your test to run.
I have faced the same problem. I recommend you NOT to use MongoRepository to access to MongoDB for several reasons:
It is used for easy queries, like findByxxx or findOneByxxxAndyyy. If you want more complex query, even #Query cannot give you what you want.
It is easy to make syntax mistake, because all query conditions are defined by interface.
Cannot define dynamic queries, like search depending on context, fields, aggregations, etc...
Instead, I recommend you to use MongoOperations. It accepts dynamic query with simple/complex criteria, very easy syntax to write your query, etc... For mocking, use Fongo framework, so it is 100% in memory database, so you can do all CRUD operations for asserts...
More info: http://docs.spring.io/spring-data/data-mongo/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html
How to mock
https://github.com/fakemongo/fongo#usage-details
UPDATE:
If you still need to mock MongoDB repository, use this xml definition:
mongo-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<bean name="fongo" class="com.github.fakemongo.Fongo">
<constructor-arg value="InMemoryMongo" />
</bean>
<bean id="mongo" factory-bean="fongo" factory-method="getMongo" />
<mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" />
<!-- localhost settings for mongo -->
<!--<mongo:db-factory id="mongoDbFactory" /> -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory" />
</bean>
<!-- Base package to scan the mongo repositories -->
<!-- Set your CompanyRepository package -->
<mongo:repositories base-package="package.to.repositories" />
</beans>
Define your test class by this way:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"/mongo-config.xml"})
public class CompanyTest {
#Autowired
private MongoOperations mongoOperations;
#Resource
private CompanyRepository companyRepository;
#Test
public void foo() {
// Define test logic
}
}

Categories

Resources