spring - read property value from properties file in static field of class - java

I have one utility class where i have one method which requires username and password to connect other url. I need to kept that username in properties file so that i can change it any time. But as i am using it in static method (being utility class) , Issue is it is showing null .(i.e. it is not able to read from properties file).
But when i ckecked that values in some other controller they are getting there.
So my question is how to read property value in static field
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:/myservice_detaults.properties</value>
<value>classpath*:/log4j.properties</value>
</list>
</property>
</bean>
//in Utitlity class code
#Value("${app.username}")
static String userName;
public static connectToUrl(){
//use userName
//userName showing null
}

In you Utility class you can have a setter method to set the properties and then you can use MethdInvokingFactoryBean.
class Utility{
static String username;
static String password;
public static setUserNameAndPassword(String username, String password){
Utility.username = username;
Utility.password = password;
}
//other stuff
}
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:/myservice_detaults.properties</value>
<value>classpath*:/log4j.properties</value>
</list>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="foo.bar.Utility.setUserNameAndPassword"/>
<property name="arguments">
<list>
<value>${username}</value>
<value>${password}</value>
</list>
</property>
</bean>

Or using the #Value over the non-static setter method for username
eg.
#Value("${app.username}")
public void setUserName(String userName) {
UtilityClass.userName = userName;
}

Read property value from properties file in static field of class using Java based spring configuration.
Example :
// The property file to store fields.
user.properties
username=Elijah Wood
age=26
language=English
// This class holds the static values
package org.javahive.propertyreader.example;
public class UserDetails {
static String username;
static String age;
static String language;
public static void setUserValues(String username, String age, String language) {
UserDetails.username = username;
UserDetails.age = age;
UserDetails.language = language;
}
}
//Spring configuration class
package org.javahive.propertyreader.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
#Configuration
#ComponentScan(value = { "org.javahive.propertyreader.example" })
#PropertySource("classpath:user.properties")
public class PropertyReaderConfig {
#Value("${user}")
private String username;
#Value("${age}")
private String age;
#Value("${language}")
private String language;
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
MethodInvokingFactoryBean mifb = new MethodInvokingFactoryBean();
mifb.setStaticMethod("org.javahive.propertyreader.example.UserDetails.setUserValues");
mifb.setArguments(new String[] { this.username, this.age, this.language });
return mifb;
}
/**
* #return the name
*/
public String getName() {
return username;
}
/**
* #param name
* the name to set
*/
public void setName(String name) {
this.username = name;
}
/**
* #return the age
*/
public String getAge() {
return age;
}
/**
* #param age
* the age to set
*/
public void setAge(String age) {
this.age = age;
}
/**
* #return the language
*/
public String getLanguage() {
return language;
}
/**
* #param language
* the language to set
*/
public void setLanguage(String language) {
this.language = language;
}
}
//The main class.
package org.javahive.propertyreader.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(PropertyReaderConfig.class);
System.out.println("User Name : " + UserDetails.username);
System.out.println("Age : " + UserDetails.age);
System.out.println("Language : " + UserDetails.language);
}
}

Try this :
Make your class a Component
#Component
public class UserXXXUtils {
private static Integer trustXXXMask;
#Value("${trustXXXMask}")
public void setTrustXXXMask(Integer trustXXXMask) {
UserXXXUtils.trustXXXMask = trustXXXMask;
}
//Access anywhere in the class
}

Spring doesn't allow to inject values into non-final static fields but make your field private and it should works.

Or just
<bean id="constants" class="com.foo.constants.CommonConstants">
<property name="username" value="${username}"/>
</bean>

Related

Invalid property 'name' of bean class [Country]: Bean property 'name' is not writable or has an invalid setter method. Did you mean 'cname'?

I am new to springs, so I was just trying to implement inheritance in spring.
Customer.java
public class Customer {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Country.java
public class Country {
String cname;
String city;
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String args[]){
ApplicationContext context = new ClassPathXmlApplicationContext("Bean1.xml");
Customer cus = (Customer) context.getBean("customer");
System.out.println(cus.getName());
Country con = (Country) context.getBean("country");
System.out.println(con.getCname());
}
}
Bean1.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-3.0.xsd">
<bean id = "customer" class = "Customer">
<property name = "name" value = "Garima"/>
</bean>
<bean id ="country" class="Country" parent="customer">
<property name = "cname" value = "India"/>
<property name = "city" value = "Delhi"/>
</bean>
</beans>
Every time I run this without parent in Bean1.xml, this is running fine. As soon as I add parent , I receive the below mentioned error.
Error : Invalid property name of bean class [Country]: Bean property name is not writable or has an invalid setter method. Did you mean cname?
I have noticed this case with many other examples as well.
Can someone please help me with this?
This is because your bean definition suggests that Customer is parent of Country but your class Country doesn't extend Customer
<bean id ="country" class="Country" parent="customer">
So you have two options
Either remove parent="customer" from your bean definition
OR Extend Customer in Country class like
public class Country extends Customer{...

Address value shows null

I have two classes Student and Address which implements IStudent ans IAddress interfaces respectively. Student class has a relationship with Address class. That is why i have declared a reference member of it.
public class Student implements IStudent {
private String code;
private String name;
#Autowired
private IAddress address;
#Override
public String getCode() {
return this.code;
}
#Override
public String getName() {
return this.name;
}
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public IAddress getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
and I have Address class
public class Address implements IAddress{
private String city;
private String pinCode;
private String houseNo;
private String roadName;
#Override
public String getCity() {
return this.city;
}
#Override
public String getPinCode() {
return this.pinCode;
}
#Override
public String getHouseNo() {
return this.houseNo;
}
#Override
public String getRoadName() {
return this.roadName;
}
public void setCity(String city) {
this.city = city;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public void setRoadName(String roadName) {
this.roadName = roadName;
}
}
In my applicationContext.xml file i have written the following bean definitions
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
</bean>
<bean id="addressbean" class="main.Address">
<property name="houseNo" value="119/2"></property>
<property name="roadName" value="South Avenue"></property>
<property name="city" value="Delhi"></property>
<property name="pinCode" value="110005"></property>
</bean>
</beans>
When i have checked Student object after initialization of bean, name and code has assigned with setter method. But the address is not assigned. Thus it shows null value for address. I have marked address with #Autowired annotation. Can you please help?
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) factory.getBean("studentbean");
System.out.println(student.getAddress());
you need to explicitly wire to Address not IAddress since the CI only knows Address, if you want to wired
#Autowired
private Address address;
or you need to define a bean with type IAddress but make sure you do not have more than implementation or spring will get confused, if you have more than one implementation use can qualifiers to clear the ambiguity
This whole example is kind of strange but you can get rid of the #Autowired annotation and use following bean configuration instead;
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
<property name="address" >
<ref local="addressbean"/>
</property>
</bean>

Custom Validation messages spring not being displayed

I am currently using the following environment:
Netbeans 8
Jdk 1.7
Spring 4
Hibernate 5.0.1
Bean validator 1.1
I have got the following files:
Servlet configuration (Spring):
<context:component-scan base-package="mz.co.hypervision.web" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
Student class:
public class Student {
#NotNull(message = "{age.notnull}")
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Message properties file:
Location: SpringTest\build\web\WEB-INF\classes
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
age.notnull=The age of the student may not be null
UPDATED
Controller code:
import javax.validation.Valid;
import mz.co.hypervision.domain.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
#Controller
public class StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "student", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("student") #Valid Student student,
BindingResult result, ModelMap model) {
if(result.hasErrors()) {
return "student";
} else {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
}
Please check below that the message appears as {age.notnull}:
Image with the situation
Please assist in figuring out why it is not working, as per my view I have followed every step to make it happen
The issue was solved by adding the messages.properties file to the java classpath

No constructor with 3 arguments defined in class?

Let me clear it, I'm a completely beginner in Spring framework.
I've three class files, Now i'm getting an error into beans.xml. You could take a look into my codes.
Here is MyAddress.java:
package com.project;
public class MyAddress {
private String city;
private String state;
private String address;
public void Address(String city, String state, String address){
this.city=city;
this.state=state;
this.address=address;
}
public String toString(){
return city+" "+state+" "+address;
}
}
Here is my Employee.java
package com.project;
public class Employee {
private int id;
private String name;
private MyAddress address;
public Employee(){
System.out.print("Default constructor..");
}
public void Employee(int id, String name, MyAddress address){
this.id=id;
this.name=name;
this.address=address;
}
public void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
}
Here is my MainProgram.java
package com.project;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainProgram {
public static void main(String[] args){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
Employee em=(Employee)ac.getBean("e");
em.show();
}
}
and finally here is my beans.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">
<bean id="e" class="com.project.MyAddress">
<constructor-arg value="USA" type="String"></constructor-arg>
<constructor-arg value="Delhi" type="String"></constructor-arg>
<constructor-arg value="Bangalore" type="String"></constructor-arg>
</bean>
<bean id="e2" class="com.project.Employee">
<constructor-arg value="123" type="int"></constructor-arg>
<constructor-arg value="raj"></constructor-arg>
<constructor-arg>
<ref bean="e"/>
</constructor-arg>
</bean>
</beans>
I'm getting an error in beans.xml files as No constructor with 3 arguments defined in class
PLease help, what's that mean?
Surely, help would be appreciated!!
This
public void Address(String city, String state, String address)
should be
public MyAddress(String city, String state, String address)
You got the class name wrong in your constructor, and in addition, constructors don't have a return type.
You have a similar error for Employee :
public void Employee(int id, String name, MyAddress address)
should be
public Employee(int id, String name, MyAddress address)
As defined here,
"A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type"
In the MyAddress class instead of creating a constructor you created a Address method,
changing public void Address(...) to public MyAddress(...) will make it work
The address class has a default constructor. Omit void keyword from method.

I am getting NullPointer Excpetion how to resolve it.I am using Spring 3.0 and jdbcTemplate

//here I define all classes and interface which i used
//Service interface
public interface CustomerService {
public void addCustomer(CustomerTO cto);
}
//Service class implementation
public class CustomerServiceImpl implements CustomerService {
#Autowired
CustomerDAO cdao=null;
public void addCustomer(CustomerTO cto){
cdao.addCustomer(cto);
}
}
//CustomerTO Class
public class CustomerTO {
private int cid;
private String cname;
private String email;
private long phone;
private String city;
public CustomerTO(int cid, String cname, String email, long phone,
String city) {
this.cid = cid;
this.cname = cname;
this.email = email;
this.phone = phone;
this.city = city;
}
//Setter and Getters
public class JdbcCustomerDAO implements CustomerDAO {
#Autowired
JdbcTemplate jdbcTemp;
public void addCustomer(CustomerTO cto){
String sql="insert into customer values(?,?,?,?,?)";
Object ar[]={cto.getCid(),cto.getCname(),cto.getEmail(),cto.getPhone(),cto.getCity()};
jdbcTemp.update(sql,ar);
}
//Client COde
public class Lab24Client {
public static void main(String[] args) {
ApplicationContext ctc=new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerService c=(CustomerService)ctc.getBean("cs");
//add Customer
CustomerTO cust=new CustomerTO(102,"vsa","vsa#gmail.com",6154,"Pune");
c.addCustomer(cust);
}
//CustomerDAO
public interface CustomerDAO {
public void addCustomer(CustomerTO cto);
}
//spring ApplicationContext.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="dataSource class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/vik"/>
<property name="username" value="root"/>
</bean>
<bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate" autowire="constructor"/>
<bean id="cdao" class="com.jlc.JdbcCustomerDAO"/>
<bean id="cs" class="com.jlc.CustomerServiceImpl"/>
//CustomerRowMapper
public class CustomerRowMapper implements RowMapper<CustomerTO>{
#Override
public CustomerTO mapRow(ResultSet rs, int rn) throws SQLException {
CustomerTO cto=new CustomerTO();
cto.setCid(rs.getInt(1));
cto.setCname(rs.getString(2));
cto.setEmail(rs.getString(3));
cto.setPhone(rs.getLong(4));
cto.setCity(rs.getString(5));
return cto;
}
}
//when I am running the client i got following excpetion
Exception in thread "main" java.lang.NullPointerException
at com.spring.CustomerServiceImpl.addCustomer(CustomerServiceImpl.java:11)
at com.spring.Lab24Client.main(Lab24Client.java:12)
//Please tell me what mistake i did with code or what's the problem in following program
You have to enable/register annotation config like below code in your xml.
<context:annotation-config/>

Categories