Vaadin和Spring集成 - @Inject不起作用

时间:2014-01-21 21:58:54

标签: spring integration vaadin inject

我正在尝试将Vaadin与Spring集成。在我的主要Vaadin应用程序类中,我有:

public class MyVaadinApplication extends UI {

@Inject
private PrivatePersonBo privatePersonBo;

@Override
public void init(VaadinRequest request) {
    Layout layout = new FormLayout();
    layout.setCaption("New Private Person");
    setContent(layout);

    ApplicationContext appContext = new ClassPathXmlApplicationContext("resources/spring/Context.xml");
    appContext.getBean(MyVaadinApplication.class);
    PrivatePersonBo privatePersonBo = (PrivatePersonBo) appContext.getBean("privatePersonBo");
    PrivatePerson existingEmployee = privatePersonBo.findByName("TestUserName");

}

}

如果我直接从上下文获取bean,我会收到bean,但是如果我评论从appContext接收bean的行,则@Inject注释不起作用,我得到NullPointerException。我的部署描述符如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
     version="3.0">

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

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

<servlet>
    <servlet-name>VaadinApplicationServlet</servlet-name>
    <servlet-class>com.vaadin.server.VaadinServlet</servlet-class>
    <init-param>
        <param-name>UI</param-name>
        <param-value>pl.adamsalata.MyVaadinApplication</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>VaadinApplicationServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以通过两个简单步骤将Vaadin 7与Spring集成:

1)在春季环境中创建一个UIProvider查找UIs

public class SpringUIProvider extends DefaultUIProvider {

     @Override
     public UI createInstance(UICreateEvent event) {
         ApplicationContext ctx =  WebApplicationContextUtils
              .getWebApplicationContext(VaadinServlet.getCurrent().getServletContext());

         return ctx.getBean(event.getUIClass());
     }
}

2)在web.xml中声明UIProvider

<context-param>
                <param-name>UIProvider</param-name>
                <param-value>org.example.SpringUIProvider</param-value>
</context-param>

请记住将原型范围用于UI类。

答案 1 :(得分:0)

如果您想将Vaadin与Spring集成,请使用@Configurable功能。然后,所有实例化的对象(即使您使用新的MyObject()代码创建它们)也将与Spring上下文集成。您可以在Spring文档中找到有关此类设置的更多详细信息:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-using-aspectj