Spring autowired bean为null NULL

时间:2014-07-17 18:34:59

标签: spring javabeans dao autowired jdbctemplate

为什么我的bean是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]控制器[/ B]

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

@Autowired     private CommandFactory commandFactory;

@覆盖         public void init(ServletConfig servletConfig)抛出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 - 这是autowared TestService bean。在IDEA,它看起来不错。但是在调试模式下,我的testService为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]
这里我使用JdbcDaoSupport,数据源注入构造函数。

@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;

命令

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

1 个答案:

答案 0 :(得分:0)

如何创建LoginCommand对象?

Spring使用Autowired来注入正确的bean。因此只有在Spring创建LoginCommand时才有效。如果您执行了新操作,或者如果您在没有与Spring正确集成的情况下使用其他框架,这可以解释您的问题(例如没有the proper configuration的Jersey 2)。

编辑:

顺便说一句,你可以&#34; @必需&#34;注解。这不会解决您的问题,但新的错误消息可以帮助您了解发生的情况(特别是它将有助于查看是否真的由Spring创建了LoginCommand对象,并且如果自动装配失败[我认为]因为TestService的实例未找到[包命名问题,类加载器问题等]。)

您是否检查了所有组件是否在&#34; by&#34;包(在组件扫描中指定)?