Search code examples
springjavabeansdaoautowiredjdbctemplate

Spring autowired bean is null NULL


Why my beans is null?

[b]servlet-context.xml [/b]

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd"
        >
   <!-- <context:annotation-config/>-->
    <context:component-scan base-package="by"/>
    <context:property-placeholder location="classpath:database.properties"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url"  value="jdbc:mysql://localhost:3306/javakava"/>
        <property name="username" value="root"/>
        <property name="password" value="admin"/>
    </bean>
</beans>

[b]controller[/b]

public class Controller extends HttpServlet {
    private static final long serialVersionUID = 1L;

@Autowired private CommandFactory commandFactory;

@Override public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig);

    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {

        performAction(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        performAction(request, response);
    }

    private void performAction(HttpServletRequest request,
                               HttpServletResponse response) throws ServletException, IOException {

        String page = null;
        String paramPage = request.getParameter(Constants.PARAM_PAGE);
        try {
            if (paramPage != null && !paramPage.isEmpty()) {

                       Command command = commandFactory.getCommand(paramPage);
                        page = command.execute(request);


            //    Commands c = Commands.valueOf(paramPage);
              //  Command command = c.getCommandClass().newInstance();
                page = command.execute(request);
                RequestDispatcher requestDispatcher = request
                        .getRequestDispatcher(page);
                requestDispatcher.forward(request, response);
            } else {
                throw new IllegalAccessError(
                        "Error with access to class from Controller.java");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

LoginCommand - Here is autowared TestService bean. In IDEA it's look's good. But in debug mode my testService is null..

@Component
public class LoginCommand implements Command {
    @Autowired
    TestService testService;


    public String execute(HttpServletRequest request) {
        DaoCheckUserImpl id = new DaoCheckUserImpl();

        String pass = request.getParameter(Constants.PASS);
        String login = request.getParameter(Constants.LOGIN);

        id.checkUser();
        String userN = id.getUserN();
        String userP = id.getUserP();
        String userRole = id.getUserRole();
        int userId = id.getUserId();

        if (userN.equals(login) & userP.equals(pass) & userRole.equals("admin")) {
           /*
           *
           *    Here testService is null[/b]
            *
           */

           List<Test> tests =  testService.getAllTests();
            request.setAttribute(Constants.TESTS, tests);
            User user = new User();
            user.setLogin(login);
            request.getSession().setAttribute(Constants.USER, user);

            return Constants.MAIN_ADMIN_PAGE;
        } else {

            }
            return Constants.ERROR_LOGIN_PAGE;

        }
    }
}

TestService

@Service
public class TestService {

    @Autowired
    public DaoTestImpl daoTestImpl;

    public List<Test> getAllTests() {

        return daoTestImpl.getAllTests();
    }

    public Test selectTest(String idTest) {
        return daoTestImpl.selectTest(idTest);
    }

    public void deleteTest(Test test) {
        daoTestImpl.deleteTest(test);

    }

[b]DaoTestImpl [/b]
Here I using JdbcDaoSupport , datasource injected with constructor.

@Component
public class DaoTestImpl extends JdbcDaoSupport implements DaoTest  {

    @Autowired
    public DaoTestImpl(DataSource dataSource) {
        setDataSource(dataSource);
    }
...

 public List<Test> getAllTests() throws DAOException {
        return getJdbcTemplate().query(("SELECT *FROM tests"), rowMapper);
    }

CommandFactory

@Component
public class CommandFactory {
    @Autowired
    public LoginCommand loginCommand;
    public Command getCommand(String paramPage) {
        Commands command = Commands.valueOf(paramPage.toUpperCase());

        switch (command) {

        case LOGIN_COMMAND:
            return  loginCommand;

commands

public enum Commands { LOGIN_COMMAND
    /*login_Command(LoginCommand.class),

Solution

  • How do you create LoginCommand object?

    Autowired is used by Spring to inject the correct bean. So it works only if LoginCommand is created by Spring. If you performed a NEW, or if you use another framework without a proper integration with Spring, this can explain your issue (for example Jersey 2 without the proper configuration).

    EDIT:

    By the way, you can had "@Required" annotation. This will not fix your problem, but the new error message can help you to understqnd what happen (in particular it will help to see if LoginCommand object is really created by Spring and if the autowired failed [as I think] because the instance of TestService was NOT found [package naming issue, classloader issue, etc.])

    Did you check if all your components are in the "by" package (that is specified in component-scan)?