Unable to established database connection in Spring MVC using annotation and java based configuration

1k views Asked by At

I am creating a Spring MVC application that established the database connection with MySQL database. I have used java based configuration. But I don't know why DataSoruce is coming null.

Can somebody tell where I am doing wrong?

The class where I have configured my front controller.

public class FontControllerConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {

        return new Class[] { WebMvcConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {

        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

The class where I have to enable Spring MVC features.

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "controller")
public class WebMvcConfig {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver vr = new InternalResourceViewResolver();

        // set location of views.
        vr.setPrefix("/");

        // set the extension of views.
        vr.setSuffix(".jsp");

        return vr;
    }

}

Creating database connection

public class DbManager {

    @Bean
    public BasicDataSource getDataSource() {
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName("com.mysql.jdbc.Driver");
        bds.setUrl("jdbc:mysql://localhost:3306/local");
        bds.setUsername("root");
        bds.setPassword("");

        return bds;
    }

    @Autowired
    private DataSource ds;


    public void setDs(DataSource ds) {
        this.ds = ds;
    }

    public Connection conn() throws SQLException {

        Connection conn = ds.getConnection();

        return conn;

    }

}

and the final controller class that handles user request for checking whether the connection established or not.

@Controller
public class MyController {

    @RequestMapping("/check")
    public ModelAndView greet() throws SQLException {

        DbManager dbMan = new DbManager();

        if (dbMan.conn() != null) {
            return new ModelAndView("welcome", "msg", "SUCCESS");
        } else {
            return new ModelAndView("welcome", "msg", "FAIL");
        }

    }

}

Thanks in advance :)

2

There are 2 answers

0
Sachin On BEST ANSWER

The mistake that can be seen is that you missed @Configuration annotation on DbManager.class

Another thing that i want to point out is "setDs" method, you don't need this as this is basically what @Autowired is doing, it is also your next mistake, you have to get the instance of DbManager from spring using @Autowired.

@Autowired
private DataSource dbMan;

 @RequestMapping("/check")
public ModelAndView greet() throws SQLException {

    //DbManager dbMan = new DbManager();

    if (dbMan.conn() != null) {
        return new ModelAndView("welcome", "msg", "SUCCESS");
    } else {
        return new ModelAndView("welcome", "msg", "FAIL");
    }

}

if still your connection is not crating then make sure.

  1. Is DbManager.class is in the package which you have given in @ComponentScan annotaion.
1
Matthias On

When you instantiate DbManager yourself, spring can't intercept and do the autowiring for you. Therefore the Datasource will be empty.

To fix this:

  • first add a @Configuration annotation to DbManager - then Spring will automatically recognize it as a bean factory and instantiate it for you. (you will probably see an error first while doing that, because DbManager tries to Autowire a bean that it's creating itself. just drop the @Autowired from the class and the reference to the datasource altogether.
  • let Spring autowire the datasource into your controller (e.g. by constructor or field injection).

Hope this helps

Matthias