wannabeartist
wannabeartist

Reputation: 2833

Can you set properties to beans when using component-scan?

Is it possible to set properties to beans when they are auto-detected?

I have a bean which would need to read a text file and I'd like to inject the path, but this bean is part of a web app where all beans are auto-detected.

Upvotes: 3

Views: 1408

Answers (1)

NimChimpsky
NimChimpsky

Reputation: 47290

Yes just inject them using @Value annoation, eg :

@Service("myService")
public class MyService

    @Value("${myProperty}")
    String whatever;
...

and then in app context :

<context:property-placeholder
  location="classpath:application.properties"
  ignore-unresolvable="true"
/>

stick file application.properties containing your string vars in your classpath (normally via src/main/resources).

Or you could just make sure your file is on classpath, and reference that as classpath resource

final org.springframework.core.io.Resource myFile = new ClassPathResource("MyTextFile.text");

Upvotes: 3

Related Questions