Liferay 7.2中的Spring自动装配注释

时间:2019-07-11 11:58:47

标签: java spring autowired liferay-7

大家好

我想在带@Autowired注释的liferay 7.2中使用spring-core。所以,我有下一个portlet

package com.aimprosoft.module;

import com.aimprosoft.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import java.io.IOException;

public class SamplePortlet  extends GenericPortlet {

    @Autowired
    private EmployeeService employeeService;

    @Override
    protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
        response.getWriter().println(employeeService.toString());
    }
}

那么,我必须在web.xml或portlet.xml中做什么才能设置spring-core的上下文侦听器? 例如,在Web-Servlet应用程序中,我必须添加

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

1 个答案:

答案 0 :(得分:0)

实际上是春季版本中的问题

我使用了不支持Java 8的3.2.0。当我切换到4.0.0时,一切正常。

总结。对于liferay portlet项目中的spring核心,我必须:

  • 将上下文侦听器添加到我的WEB-INF / web.xml文件中
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/applicationContext.xml</param-value> 
</context-param>
  • 然后在每个portlet中使用以下方法初始化@Autowired字段
@Override
public void init() throws PortletException {
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
  • 我有以下持久性单元
<persistence-unit name="departments">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.aimprosoft.dao.model.Employee</class>
    <class>com.aimprosoft.dao.model.Department</class>
    <properties>
        <property name="hibernate.connection.username" value="username"/>
        <property name="hibernate.connection.password" value="password"/>
        <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/departments"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
    </properties>
</persistence-unit>
  • 最后一个春天的背景如下
<context:annotation-config/>
<context:component-scan base-package="com.aimprosoft"/>
<bean id="departments" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceXmlLocation" value="WEB-INF/persistence.xml"/>
</bean>
<bean id="textResource" class="java.util.ResourceBundle" factory-method="getBundle">
    <constructor-arg value="text_bundle"/>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>