@ServerEndpoint和Spring MVC注入

时间:2016-10-28 22:00:39

标签: java spring-mvc websocket

我试图在@ServerEndpoint类中注入@Repository类注释。但是当我试图调用存储库方法时,它返回null。来自这个包的另一个注入的bean工作正常。

@ApplicationScoped
@ServerEndpoint("/WebsocketHome/actions")
public class WebSocketServer {
private static final Logger LOG = Logger.getLogger(WebSocketServer.class);

@Inject
private SessionHandler sessionHandler;

@Inject
private PlaceRepository placeRepository;

@OnMessage
public void handleMessage(String message, Session session) {

    JSONParser jsonParser = new JSONParser();

    try {
        JSONObject jsonObject = (JSONObject) jsonParser.parse(message);

        if ("getRooms".equals(jsonObject.get("action"))) {
            List<Place> places = this.placeRepository.getAllPlaces(); //error is here               
        }
        } catch (ParseException e) {
            LOG.error(e.getMessage());
        }
.....

这是存储库类:

@Repository
@Transactional
public class PlaceRepository {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public List<Place> getAllPlaces() {
        return this.sessionFactory.getCurrentSession().createQuery("from Place place").list();
    }
}

web.xml中:         

<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">
    <display-name>Archetype Created Web Application</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>

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

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</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>

</web-app>

APP-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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:application.properties" system-properties-mode="ENVIRONMENT"/>
    <context:component-scan base-package="com.hms.repository"/>
    <context:component-scan base-package="com.hms.utils"/>
    <tx:annotation-driven transaction-manager="txManager"/>

   <import resource="security-context.xml"/>

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

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${db.driverClassName}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
        <!--
        <property name="initialSize" value="5" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
        <property name="minIdle" value="2" />
        -->
    </bean>

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${db.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hbm2ddl.auto">${db.hbm2ddl.auto}</prop>
            </props>
        </property>
    </bean>
</beans>

仅在调用@OnMessage方法时出现错误。 所有junit @Tests of repository类都会返回很好的结果。 我的代码有什么问题? 抱歉我的英文。

UPD:

看来,问题在于SessionFactory依赖,因为我在@Repository中添加了测试方法:

public String testWS() {
        return "Test is ok!";
    }

返回精美的结果。

1 个答案:

答案 0 :(得分:1)

所以,看起来我找到了正确的方法。我在Spring websocket documentation找到了它。 我做了一些步骤:

  1. 我输入了类型级别的注释:

    @ServerEndpoint(value =“/ WebsocketHome / actions”,configurator = SpringConfigurator.class)

  2. 我将@Service和@Controller添加到我的websocket类和我的app-context.xml文件的“context:component-scan”路径,以便Spring可以找到相应的bean。

  3. 我在我的pom.xml中添加了“spring-websocket”依赖项(我使用maven)

  4. 也许这不是正确的方法,但它对我来说很好。