不要在 Spring 中使用@autowire

Don't work @autowire in Spring

我想自动连接我的 userService,但出现错误。我有:

web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>

调度员-servlet.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:sec="http://www.springframework.org/schema/security"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

<context:annotation-config/>
<context:component-scan base-package="com.andrylat.rgz.ocean.controllers" />
<context:component-scan base-package="com.andrylat.rgz.ocean.services" />

<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/"/>

<tx:annotation-driven />   

申请-context.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:sec="http://www.springframework.org/schema/security"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
   http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

<!-- DataAccess -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:XE"/>
    <property name="user" value="rgz1002"/>
    <property name="password" value="aqweds"/>
</bean>


<context:component-scan base-package="com.andrylat.rgz.ocean.dao"/>
<!-- Hibernate session factory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
            <property name="packagesToScan">
                <list>
                    <value>com.andrylat.rgz.ocean.domains</value>

                </list>
            </property>
    <property name="hibernateProperties">
        <props>
        <prop key="hibernate.dialect">
                       org.hibernate.dialect.Oracle10gDialect
                    </prop>
        <prop key="hibernate.format_sql">true</prop>
        <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

    <context:component-scan base-package="com.andrylat.rgz.ocean.domains"/>

<bean id="userDAO" class="com.andrylat.rgz.ocean.dao.UserDAOImpl">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="userService" 
            class="com.andrylat.rgz.ocean.services.UserService">
    <property name="userDAO" ref="userDAO" />
</bean>

    <bean id="userServiceForSecurity" 
            class="com.andrylat.rgz.ocean.services.UserService">
    <property name="userDAO" ref="userDAO" />
</bean>


<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <tx:method name="get*" read-only="true" />
    <tx:method name="find*" read-only="true" />
    <tx:method name="*" />
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:pointcut id="userServicePointCut"
    expression="execution(* com.andrylat.rgz.ocean.services.*Service.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
</aop:config>   

<!-- Spring Security -->
<bean id="passwordEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
</bean>

<sec:http auto-config="true" use-expressions="true">

    <!--access-denied-handler error-page="/403" /-->

    <sec:logout logout-success-url="/index.htm" />

    <sec:form-login login-page="/login.htm" 
                    default-target-url="/Ocean/test/testpage.htm" 
                    authentication-failure-url="/login.htm?error=1" />

    <sec:intercept-url pattern="/test/*"
        access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
    <sec:intercept-url pattern="/*"
        access="permitAll" />
    <sec:intercept-url pattern="/resources/**"
        access="permitAll" />
    <sec:csrf />
</sec:http>

<!--sec:authentication-manager>
    <sec:authentication-provider>            
        <sec:jdbc-user-service data-source-ref="dataSource"
      users-by-username-query=
        "select login, password, enabled from users where login =? "
      authorities-by-username-query=
        "select login, userrole from userroles where login =? " />            

        <sec:password-encoder ref="passwordEncoder" />            
    </sec:authentication-provider>
</sec:authentication-manager-->

<sec:authentication-manager>
    <sec:authentication-provider user-service-ref="userServiceForSecurity" >
        <sec:password-encoder ref="passwordEncoder" />    
    </sec:authentication-provider>
</sec:authentication-manager>

UserService.java

@Service("userService") public class UserService implements UserDetailsService {

@Autowired
private UserDAO userDAO;

public UserDAO getUserDAO() {
    return userDAO;
}

public void setUserDAO(UserDAO userDAO) {

    this.userDAO = userDAO;
}



@Transactional(readOnly = true)
@Override
public UserDetails loadUserByUsername(final String username)
        throws UsernameNotFoundException {

    com.andrylat.rgz.ocean.domains.User user = userDAO.findByUserName(username);
    List<GrantedAuthority> authorities
            =  new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(user.getRole ()));

    return buildUserForAuthentication(user, authorities);
}

private User buildUserForAuthentication(com.andrylat.rgz.ocean.domains.User user,
        List<GrantedAuthority> authorities) {
    return new User(user.getLogin(), user.getPassword(),
            user.getEnabled(), true, true, true, authorities);
}}

IndexController.java

@Controller public class IndexController {

//@Autowired
//@Qualifier("userService")
private UserService userService;

public UserService getUserService() {
    return userService;
}

public void setUserService(UserService userService) {
    this.userService = userService;
}

@Autowired
private SessionFactory sessionFactory;


@RequestMapping (value="/index", method=RequestMethod.GET)
private ModelAndView getIndexPage (){
    if (sessionFactory==null) {
        System.err.println("sessionFactory is null!");
    } else {
        System.err.println("sessionFactory OK!");
    }
    return new ModelAndView ("index");
}

@RequestMapping (value="/login", method=RequestMethod.GET)
private ModelAndView getLoginPage (){
    return new ModelAndView ("login");
}    }

问题: 我在 IndexController.java 中的 UserService 没有自动装配!我被添加 "sessionFactory" 并且它也没有自动装配。 "SessionFactory" 仅为空,当我向 UserService 写入注释时,我有下一个堆栈跟踪(来自 jsp):

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.andrylat.rgz.ocean.services.UserService com.andrylat.rgz.ocean.controllers.IndexController.userService; nested exception is java.lang.IllegalArgumentException: **Can not set com.andrylat.rgz.ocean.services.UserService field com.andrylat.rgz.ocean.controllers.IndexController.userService to com.sun.proxy.$Proxy158**
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:296)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:602)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:521)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:462)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)

我不明白为什么我无法获取此 UserService 并且我的 sessionFactory 为空。

似乎是应用程序的问题-context.xml命名。

因此,请确保文件 applicationContext.xml 在 WEB-INF 文件夹中存在且名称正确(不应为 application-context.xml),以便加载 sessionFactory bean。否则,sessionFactory bean 对象将为空。

错误出现在

private UserService userService;

UserService 是 class 而不是界面。我创建接口 UserServiceI(UserService 是实现 UserServiceI)并写入 IndexController

@Autowire
private UserServiceI userService;

一切正常!