Spring + Jersey无法正确加载spring-config.xml(Autowired beans为null)

时间:2016-12-22 10:44:14

标签: java spring rest spring-mvc jersey

我正在使用Jersey和Spring制作REST API。我正在尝试在spring-config.xml文件中加载名为web.xml的弹簧的应用程序上下文。

场景1:我将此文件放在/WEB-INF下并设置<param-value>/WEB-INF/spring-config.xml</param-value>,一切都按预期工作,没有遇到任何问题。

场景2:我将spring-config.xml放在src/main/resources中(即类路径)并设置<param-value>classpath*:spring-config.xml</param-value>。在这种情况下,我的应用程序已成功部署。但是例如说我尝试对http://localhost:8000/rest/authenticate进行POST调用,我收到以下错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type "club.myfpl.services.UserService" available: expected at least 1 bean which qualifies as autowire candidate.

请帮我弄清楚为什么在WEB-INF中放置我的spring-config.xml并将其放在src/main/resources中不行。仅供参考,如果重要的话,我正在使用Intellij。

我的球衣资源档案:

@Path("/authenticate")
@Service
public class AuthenticationRestAPI {

    @Autowired
    UserService userService;

    @POST
    @Produces("application/json")
    @Consumes("application/x-www-form-urlencoded")
    public Response authenticateUser(@FormParam("email") String email, @FormParam("password") String password) {
        try {
            // Authenticate the user using the credentials provided
            authenticate(email, password);
            // Issue a token for the user
            String token = issueToken(email);
            // Return the token on the response
            return Response.ok(token).build();
        } catch (Exception e) {
            return Response.status(Response.Status.UNAUTHORIZED).build();
        }
    }

    private void authenticate(String email, String password) throws Exception {
        if (!userService.authenticateUser(email, password)) {
            throw new Exception();
        }
    }

    private String issueToken(String email) throws Exception {
        User user = userService.fetchUserByEmail(email);
        String token = JWT.create()
                .withIssuer(SecurityConstants.JWT_ISSUER)
                .withExpiresAt(Date.from(LocalDate.now().plus(1, ChronoUnit.DAYS).atStartOfDay(ZoneId.systemDefault()).toInstant()))
                .sign(Algorithm.HMAC256(SecurityConstants.JWT_SECRET));
        userService.createUserAuthToken(user.getUserId(), token);
        return token;
    }
}

我的web.xml文件:

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

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring-config.xml</param-value>
    </context-param>

    <display-name>MyFPL REST API</display-name>
    <servlet>
        <servlet-name>REST API Servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>club.myfpl.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>REST API Servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

我的spring-config.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       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/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <mongo:mongo id="mongo" host="127.0.0.1" port="27017"/>
    <mongo:db-factory id="mongoDbFactory" dbname="myFpl" mongo-ref="mongo"/>
    <mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory"/>

    <context:annotation-config/>
    <context:component-scan base-package="club.myfpl"/>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>

build.gradle档案的相关部分:

dependencies {
    compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
    compile group: 'javax.el', name: 'javax.el-api', version: '3.0.0'

    compile group: 'org.glassfish.jersey.core', name: 'jersey-server', version: '2.25'
    compile group: 'org.glassfish.jersey.containers', name: 'jersey-container-servlet', version: '2.25'
    compile (group: 'org.glassfish.jersey.ext', name: 'jersey-spring3', version: '2.25') {
        exclude group: 'org.springframework'
    }

    compile group: 'org.springframework.data', name: 'spring-data-mongodb', version: '1.9.2.RELEASE'

    compile group: 'org.springframework', name: 'spring-core', version: '4.3.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-web', version: '4.3.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-context', version: '4.3.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-aop', version: '4.3.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-test', version: '4.3.4.RELEASE'
}

0 个答案:

没有答案