[JAVA] How to use Struts2 * Spring Framework (Spring plugin) June 2017 Version

How to connect Struts2 and Spring Framework

Struts2 has a DI container internally, and you can read it from the configuration file you use and instantiate the specified class. The function of DI container can be replaced with other DI container, and Spring framework and JSR-330 (Guice) can also be used. Struts2 plug-in is prepared for each container, so if you want to use DI of Spring framework, for example, install Spring plug-in.

By installing the Spring plugin, you can get the following features.

  1. Action and Validator classes enter Spring management
  2. You can access the beans managed by Spring from these classes
  3. You can also use various functions provided by Spring framework and functions to connect Spring with other frameworks.

… And that ** most can be replaced with the Spring framework and Spring subprojects **.

Unfortunately, it doesn't provide Spring Boot functionality, but it has more powerful features than the Struts2 standard DI container, so there's no reason not to use it. The corresponding Spring version is up to 4.2 series in Struts2 official, but in fact 4.3 series and later are also available so far.

How to introduce

It's easy to install, just get the plugin and add the settings.

Plugin

Introduces the exact same Struts2-Spring-plugin as the Struts2 version. The following is the case to specify with maven. Add to the child elements of <dependencies>.

pom.xml


<dependency>
	<groupId>org.apache.struts</groupId>
	<artifactId>struts2-spring-plugin</artifactId>
	<version>${struts2.version}</version>
</dependency>

Setting

There are two ways to modify the configuration file.

  1. Struts2 settings
  2. web.xml

First, add the following line to struts.properties, which is one of the Struts2 settings. The location is arbitrary.

struts.properties


struts.objectFactory=org.apache.struts2.spring.StrutsSpringObjectFactory

Next, set the Spring context and listener in web.xml (deployment descriptor). The following settings are the settings to read the classpath /spring/applicationContext.xml and the xml file starting with applicationContext- as the Spring configuration file.

web.xml


<web-app>
    <display-name>prototype_app</display-name>
    <context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:spring/applicationContext.xml,classpath:spring/applicationContext-*.xml</param-value>
    </context-param>

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

That's all for the settings to use. After this, set applicationContext.xml to register the beans to be put in Spring management.

Implementation example of Action class

Classes under Spring management can be used by @Autowired in Action class. The following example is a simple list search sample.

SampleAction.java


@Namespace("/")
@Results({@Result(name=ActionSupport.SUCCESS, location="list")})
@Log4j2
public class DisplayListAction extends ActionSupport {

    @Action("list")
    public String execute() throws Exception {
	products = service.search();
	log.info("- search:{}" , products);

        return SUCCESS;
    }

    @Autowired
    ProductService service;

    @Getter @Setter
    List<SampleProduct> products;
}

The Service class (ProductService) used from this Action class returns a fixed list like this:

ProductService.java


import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Service;

@Service
public class ProductService {
	public List<SampleProduct> search() {
		List<SampleProduct> resultList =

		Arrays.asList(
			new SampleProduct().setProduct("A-1", "Prototype X-290PA1", 10, true, true),
			new SampleProduct().setProduct("A-2", "Prototype X-290PA2", 20, true, true),
			new SampleProduct().setProduct("B-3", "Prototype X-B3", 10, true, true),
			new SampleProduct().setProduct("B-4", "Prototype X-B4", 30, true, true),
			new SampleProduct().setProduct("C-5", "Prototype X-C5", 10, true, false),
			new SampleProduct().setProduct("C-6", "Prototype X-C6", 40, true, false),
			new SampleProduct().setProduct("D-7", "Prototype X-D7", 10, false, true),
			new SampleProduct().setProduct("D-8", "Prototype X-D8", 50, false, true),
			new SampleProduct().setProduct("E-9", "Prototype X-E9", 10, true, true),
			new SampleProduct().setProduct("Z-1000", "Prototype Z-1000", 0, false, false)
		);

		return resultList;
	}
}

The Sample Product that appears here is a simple Data Transfer Object. Since it is a search result, you can make it a Value Object.

Spring bean settings: applicationContext.xml

Unfortunately JavaConfig cannot be used, so define it in the xml file. Since component-scan can be used, beans can be registered at once.

applicationContext-service.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
default-autowire="byName"
>	<!--Service class definition to be managed by Spring-->

	<context:component-scan base-package="seren.struts2.sampleapp.service" use-default-filters ="false" >
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
	</context:component-scan>
</beans>

The target of component-scan is registered the class with @Service annotation in base-package.

That's all for the settings. It's easy once you make it v (・ ω ・ |

Sample project is available on github

https://github.com/A-pZ/struts2-spring-sample

bonus

You can also use Thymeleaf3 from Struts2. You can't use Struts2 tags at all, but Thymeleaf will make it easier to write a View. It will be very useful when switching from Struts2 to Spring framework etc.

http://qiita.com/alpha_pz/items/5a43b4abb07141becbcd

Recommended Posts

How to use Struts2 * Spring Framework (Spring plugin) June 2017 Version
How to use Lombok in Spring
How to use Spring Data JDBC
How to use ModelMapper (Spring boot)
How to use BootStrap with Play Framework
How to set and use profile in annotation-based Configuration in Spring framework
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
How to use Java framework with AWS Lambda! ??
How to use Spring Boot session attributes (@SessionAttributes)
How to make Unity Native Plugin (Android version)
How to use nfs protocol version 2 with ubuntu 18.04
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
[Ruby] How to use rbenv (version `x.x.x'is not installed)
How to use CommandLineRunner in Spring Batch of Spring Boot
How to use Play Framework without using typesafe activator
How to use In-Memory Job repository in Spring Batch
[Java] How to use Map
How to use Chain API
How to lower java version
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use JUnit (beginner)
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
[Swift] How to use UserDefaults
How to use java class
How to use Swift UIScrollView
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use String [] args
[Java] How to use string.format
How to use rails join
How to use Java Map
Ruby: How to use cookies