DI SessionScope Bean in Spring Boot 2 Filter

Preface

Recently I'm doing web development with Spring Boot. I would like to manage sessions with @SessionScope as much as possible instead of using HttpSession directly. I investigated how to reference @SeesionScope beans in Filter.

Constitution

name version
macOS Catalina 10.15.4
IntelliJ IDEA 2019.3.4 (Community Edition)
Java "11.0.2" 2019-01-15
Spring Boot 2.2.6
Kotlin 1.3.71

Sample code and projects are available on GitHub. Please have a look if you like.

Conclusion

There is a lot of information and the contents of the investigation will be described later, but I will write from the conclusion first. A simple configuration could only be achieved with @Autowired.

UserInfo.kt(@SessionScope)


@Component
@SessionScope
data class UserInfo(
        var name: String?
) : Serializable

SessionFilter.kt(OncePerRequestFilter)


@Component
class SessionFilter : OncePerRequestFilter() {

    //It was the same as DI with Controller.
    @Autowired
    private lateinit var userInfo: UserInfo

    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) {
        println("name: ${userInfo.name}")
        filterChain.doFilter(request, response)
    }
}

Background to the conclusion

Although it is not a book of Spring Boot 2, it seems to be famous in the Spring area Introduction to Spring Java application development with Spring Framework DelegatingFilterProxy A method has been proposed to define in XML to register a filter in. Therefore, I decided to try the method using DelegatingFilterProxy first. I don't like the method of defining in XML, so I rewrote it in Java Config (Kotlin).

SessionFilter.kt(OncePerRequestFilter)


@Component("SessionFilter")  //I was specifying a name.
class SessionFilter : OncePerRequestFilter() {
    :
    : (Same as the code posted in the conclusion)
    :
}

WebInitializer.kt


class WebInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
    override fun getRootConfigClasses(): Array<Class<*>>? {
        return null
    }

    override fun getServletMappings(): Array<String> {
        return arrayOf("/")
    }

    override fun getServletFilters(): Array<Filter> {
        val dfp = DelegatingFilterProxy().apply {
            // SessionFilter.kt@Set the name specified in Component.
            setTargetBeanName("SessionFilter")
        }
        return arrayOf(dfp)
    }

    override fun getServletConfigClasses(): Array<Class<*>>? {
        return arrayOf(WebConfig::class.java)
    }
}

I've seen some FAQs that can't DI in `Filter, and the above countermeasures have been introduced, but in my environment Conclusion / e02cad0e81ad8ba9d73e #% E7% B5% 90% E8% AB% 96), I achieved the purpose without this description. There may be a difference between Spring MVC and Spring Boot 2, but there is too little information to investigate.

At the end

Compared to other well-known web frameworks (though I don't think it's a minor web framework), I got the impression that Spring-related information is often complicated and legacy. Therefore, I posted an article for the first time in a long time, hoping that it would be useful for something.

Recommended Posts

DI SessionScope Bean in Spring Boot 2 Filter
First Spring Boot (DI)
Use Servlet filter in Spring Boot [Spring Boot 1.x, 2.x compatible]
Set context-param in Spring Boot
Spring Boot 2 multi-project in Gradle
Introduction to Spring Boot ① ~ DI ~
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Accelerate testing of Validators that require DI in Spring Boot
Spring Boot Hello World in Eclipse
Spring Boot application development in Eclipse
Write test code in Spring Boot
What is @Autowired in Spring boot?
Implement Spring Boot application in Gradle
Thymeleaf usage notes in Spring Boot
Fitted in Spring Boot using a bean definition file named application.xml
Launch (old) Spring Boot project in IntelliJ
Build Spring Boot + Docker image in Gradle
Static file access priority in Spring boot
Output Spring Boot log in json format
Local file download memorandum in Spring Boot
Create Java Spring Boot project in IntelliJ
Use DynamoDB query method in Spring Boot
Change session timeout time in Spring Boot
File output bean as JSON in spring
SameSite cookie in Spring Boot (Spring Web MVC + Tomcat)
Test controller with Mock MVC in Spring Boot
Asynchronous processing with regular execution in Spring Boot
Run a Spring Boot project in VS Code
Output request and response log in Spring Boot
Challenge Spring Boot
How to add a classpath in Spring Boot
Java tips-Create a Spring Boot project in Gradle
Spring Boot Form
How to bind to property file in Spring Boot
Spring Boot Memorandum
Annotations used in Spring Boot task management tool
[Java] Spring DI ③
View the Gradle task in the Spring Boot project
Specify the encoding of static resources in Spring Boot
Include external jar in package with Spring boot2 + Maven3
Try using DI container with Laravel and Spring Boot
How to set Dependency Injection (DI) for Spring Boot
I checked asynchronous execution of queries in Spring Boot 1.5.9
[For beginners] DI ~ The basics of DI and DI in Spring ~
Spring Boot with Spring Security Filter settings and addictive points
[Spring boot] I thought about testable code by DI
SSO with GitHub OAuth in Spring Boot 1.5.x environment
How to use CommandLineRunner in Spring Batch of Spring Boot
Test field-injected class in Spring boot test without using Spring container
Introduce swagger-ui to REST API implemented in Spring Boot
Until you start development with Spring Boot in eclipse 2
Specify spring.profiles.active via context-param of web.xml in Spring Boot
SerializationException in Spring Boot (1 series) + spring-security-oauth2 + Redis Session + Heroku
Database environment construction with Docker in Spring boot (IntellJ)
Inject Logger in Spring
SPRING BOOT learning record 01
Spring bean life cycle
Spring Boot + Heroku Postgres
Spring Framework Summary-About DI
Spring boot memo writing (1)