views:

133

answers:

2

I have a data structure representing a CSV file containing thousands of config settings. The structure is a Java class file with instance variables to represent the records in the file (ie: a HashMap) and the state of the file (errors, warnings, etc).

These classes are not created by Spring as they have state. I would like the class to access system configuration properties which are currently handled by a Spring managed database DAO class. Usually when classes need this DAO I inject it through Spring using @Autowired. But as my data structure is not managed by Spring, how can the CSV structure class access the DAO?

The only method I can think of is when creating the data structure from the Spring managed bean to just pass in the DAO:

CSVDataStruture c = new CSVDataStruture(dao);
+3  A: 

See 6.8.1. Using AspectJ to dependency inject domain objects with Spring about using @Configurable

Another way is to get ahold of the application context (in web applications this is WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)) and get the beans using context.getBean("name"), but it is more of a workaround.

Bozho
`@Configurable` is the way to go
Paul McKenzie
+1  A: 

These classes are not created by Spring as they have state.

What makes you think that Spring cannot / should not create objects that have state?

Depending on what you are trying to do (it is hard to figure this out!) I would do one of the following:

  • Give the CSV class getters and setters for a CVS file parameter and a DAO parameter, and instantiate it using Spring DI. This assumes that the filename is available when Spring wiring occurs.

  • Create a factory class with a method that instantiates a CSV object from a file parameter. The factory class should have a getter/setter for the DAO object and be instantiated using Spring DI.

Stephen C
Thanks - think I'll try option 2. What we're doing is loading a file, validating the contents, then loading a second file and diff'ing the two files.
Marcus
#2 worked great.
Marcus