jonnie
jonnie

Reputation: 12710

How Or where Do I access my properties file

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

Upvotes: 4

Views: 3781

Answers (5)

Dnyaneshwar Tambe
Dnyaneshwar Tambe

Reputation: 41

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

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

Upvotes: 2

Caesar Ralf
Caesar Ralf

Reputation: 2234

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.
     }
}

Upvotes: 1

Reimeus
Reimeus

Reputation: 159864

Given that src/main/resources is on the classpath, you could do:

Resource resource = new ClassPathResource("/myprops.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);

Upvotes: 1

duffymo
duffymo

Reputation: 309008

Don't use a FileInputStream; use getResourceAsStream() to read it from the servlet context.

Upvotes: 0

Related Questions