Spring web app database access outside managed beans

In my web app i have an applicationContext.xml which i define beans database connection parameters etc. While i can make desired operations with managed beans (using services and daos) in a pojo class; i can not use those services and managed beans. Is there a way to access database from a pojo using parameters in application context? Every example i look using @managedProperty and managed beans. However it would be a bad design to define my pojo class as managed bean.


You could inject the DataSource into the POJO (which is not normally managed by Spring) using the @Configurable annotation. See a way to do that here

Personally I would avoid going down the road of accessing the DB from a POJO if at all possible

This is possible by using the existing data source bean.

Just auto wire the dataSource or use the applicationContext (helper class) to get the datasource and acquire a connection from it. Then use prepared statement to do your native sql.

private DataSource dataSource;

  public void doBla(){
    // Open a database connection using Spring's DataSourceUtils
    Connection connection = DataSourceUtils.getConnection(dataSource); // NOSONAR
    PreparedStatement countQuery = null;
    try {
        countQuery = connection.prepareStatement("//put sql here");
        ResultSet countResult = countQuery.executeQuery();
    } catch (Exception e){
        //TODO do something here...
 DataSourceUtils.releaseConnection(connection, dataSource);

ok i solved; i tried

    private static ISettingsService settingsService;
    private static ApplicationContext context;

in constructor i called

context = new ClassPathXmlApplicationContext("../applicationContext.xml");
settingsService =  (ISettingsService)context.getBean("SettingsService");

so i get the service successfully which has all crud operations i needed. btw in applicationContext.xml i have this line

<bean id="SettingsService" class="my.path.to.services.SettingsService">
    <property name="settingsDAO" ref="SettingsDAO" />

Need Your Help

Fastest MySQL operator checking for not 0 in indexed columns: > or !=


What would be the fastest way to check for not 0 in an indexed column, using:

Spring java config EJB proxy not working

java spring spring-mvc ejb-3.0

I have a problem getting EJB beans working when using Spring's java config classes.