Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Or where Do I access my properties file

Tags:

java

spring

I have a properties file myprops.properties as follows:

Wsdl=someurl
UserName=user
UserPassword=pasword
Application=appName

And inside my controller I'm trying to access to set values in my service as follows

Properties prop = new Properties();
prop.load(new FileInputStream("resources/myprops.properties"));
myService.setWsdl(prop.getProperty("Wsdl"));
myService.setUserName(prop.getProperty("UserName"));
myService.setUserPassword(prop.getProperty("UserPassword"));
myService.setApplication(prop.getProperty("Application"));

my Issue is I just do not know what path to use. Its a Spring project if that makes any difference. and Idealy I would like to have the properties file in my "src/main/resources" folder

I realise this may be very simple to some but I have tried searching for the solution both here and on Google and I cannot seem to find a solution that has helped. I've tried moving the file around the project but cannot seem to figure it out

The Error I get is

java.io.FileNotFoundException: resources\drm.properties (The system cannot find the path specified) 

any advice/explanation or even a link that clearly explains it would be great

like image 783
jonnie Avatar asked Oct 23 '25 20:10

jonnie


2 Answers

well, src/main/resources are on the classpath, you just need to do.

Properties properties = PropertiesLoaderUtils.loadAllProperties("your properties file name");

like image 200
Dnyaneshwar Tambe Avatar answered Oct 26 '25 08:10

Dnyaneshwar Tambe


If you are using spring, you could set your property placeholder.

 <context:property-placeholder location="classpath:resources/myprops.properties" />

and in your beans you can inject the values from the properteis using the @Value annotation

@Autowired
public Foo(@Value("${Wsdl}") String wsdl) {
   ...
}

in the case above I used in the constructor, but its possible to use by Autowired field/setter.

So in your service you could have something like:

@Service
public class MyService {
     private final String wsdl;
     private final String username;
     private final String password;
     private final String application;

     @Autowired
     public MyService(
         @Value("${Wsdl}") String wsdl,
         @Value("${UserName}") String username,
         @Value("${UserPassword}") String password,
         @Value("${Application}") String application
         ) {
         // set it to each field.
     }
}
like image 44
Caesar Ralf Avatar answered Oct 26 '25 09:10

Caesar Ralf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!