Showing posts with label Spring Boot. Show all posts
Showing posts with label Spring Boot. Show all posts

Friday, December 27, 2024

Smallest Working Spring Boot 3 Application with Faces 4, OmniFaces 4, and CDI 4

For reference, here is the minimal Maven project structure for a Spring Boot 3 application using Faces 4, OmniFaces 4, and CDI 4.

While Spring can function without CDI, the OmniFaces @ViewScoped annotation, with its powerful unload feature, doesn't work out of the box without CDI. Along with the CDI managed bean, we're also creating a simple @ApplicationScoped CDI service for demonstration purposes.

An alternative to Spring Boot is Quarkus. You can find it here: Smallest Working Quarkus 3 Application with Faces 4, OmniFaces 4 and CDI 4.

pom.xml

Below is the minimal Maven configuration, including the spring-boot-maven-plugin setup required to produce a Fat JAR:

<?xml version="1.0" encoding="UTF-8"?>
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
>
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.3</version>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>springboot3-omnifaces4</artifactId>
    <version>1.0.0</version>

    <dependencies>
        <dependency>
            <groupId>org.joinfaces</groupId>
            <artifactId>omnifaces-spring-boot-starter</artifactId>
            <version>5.4.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

We're using JoinFaces to auto-configure a Spring Boot 3.x application with Faces 4.x (Mojarra), OmniFaces 4.x, and CDI 4.x (Weld) with minimal effort. Noted should be that we need a minimum version of JoinFaces 5.4.3 in case you wish to be able to launch it as a Fat JAR, because in previous versions the beans.xml wasn't correctly autodiscovered, see also JoinFaces issue 2673.

src/main/java/com/example/ExampleApplication.java

The mandatory Spring Boot application configurer and launcher:

package com.example;

import jakarta.inject.Named;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;

@Configuration
@SpringBootApplication
@ComponentScan(excludeFilters = @Filter(Named.class))
public class ExampleApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

Note that the @ComponentScan is configured to exclude all classes annotated with CDI's @Named. This basically prevents Spring from auto-registering all @Named-annotated classes as Spring managed beans, hereby completely overriding CDI. Without it, any @Named-annotated class would behave as a Spring singleton bean, which is like a CDI @ApplicationScoped.

src/main/java/com/example/backing/ExampleBacking.java

The CDI managed bean representing a Jakarta Faces backing bean utilizing OmniFaces powerful @ViewScoped annotation with its memory-saving unload feature:

package com.example.backing;

import java.io.Serializable;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import jakarta.inject.Named;

import org.omnifaces.cdi.ViewScoped;

import com.example.service.ExampleService;

@Named
@ViewScoped
public class ExampleBacking implements Serializable {

    private static final long serialVersionUID = 1L;

    private String input;
    private String output;

    @Inject
    private ExampleService service;

    public void submit() {
        output = service.process(input);
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getOutput() {
        return output;
    }
}

src/main/java/com/example/service/ExampleService.java

The CDI service:

package com.example.service;

import jakarta.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class ExampleService {

    public String process(String input) {
        return "Hello! You have typed: " + input;
    }
}

Note, in case you wish this class to be a Spring-managed bean such as @Service and inject it via @AutoWired in your CDI managed bean, then you need a custom CDI extension. Detail can be found in this related article: Using OmniFaces CDI @ViewScoped with unload/destroy in a Spring Boot project.

src/main/resources/META-INF/resources/index.xhtml

The Facelet file with a basic Jakarta Faces form:

<!DOCTYPE html>
<html lang="en"
    xmlns:f="jakarta.faces.core"
    xmlns:h="jakarta.faces.html"
>
    <h:head>
        <title>Hello!</title>
    </h:head>
    <h:body>
        <h1>Hello!</h1>
        <h:form>
            <h:outputLabel for="input" value="Type something: " />
            <h:inputText id="input" value="#{exampleBacking.input}" />
            <h:commandButton value="Submit" action="#{exampleBacking.submit}">
                <f:ajax execute="@form" render=":output" />
            </h:commandButton>
        </h:form>
        <h:outputText id="output" value="#{exampleBacking.output}" />
    </h:body>
</html>

Note that web resources, such as Facelets files, must to be placed in the src/main/resources/META-INF/resources folder as if it were a web fragment JAR project rather than src/main/webapp as in a WAR project!

src/main/resources/BOOT-INF/classes/META-INF/beans.xml

The mandatory beans.xml file to activate all the things CDI such as @Named beans:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="https://jakarta.ee/xml/ns/jakartaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_4_0.xsd"
    version="4.0" bean-discovery-mode="annotated"
>
</beans>

Do note that the beans.xml needs to go into the src/main/resources/BOOT-INF/classes/META-INF folder in order to get the Fat JAR execution using java -jar command to work. In case you wish to be able to execute/debug the application by directy executing the main() method using an IDE or the mvn spring-boot:run command, then you need to place a copy of the beans.xml in the src/main/resources/META-INF folder as well.

Also note that the bean-discovery-mode is explicitly set to annotated so that CDI leaves any Spring managed beans alone, even though this is the default behavior since CDI version 4.0.

In case you wish to use a src/main/webapp folder like in a standard Maven WAR project structure, even if only in order to have a clear oversight of all the web resources and WAR-related deployment descriptors, or to avoid the need to create copies of beans.xml files, then you can always reconfigure the <build> section of your pom.xml accordingly so that all these files ultimately end up in the right locations of the produced Fat JAR file as expected by Spring Boot. A concrete example can be found in this related Stack Overflow answer: src/main/webapp is IGNORED when packaging is JAR instead of WAR.

Build and run it!

First cd into the folder where the pom.xml is located.

Now create the Fat JAR:

mvn clean package

Then execute the Fat JAR:

java -jar target/springboot3-omnifaces4-1.0.0.jar

Finally launch your default web browser on http://localhost:8080/index.xhtml:

browse http://localhost:8080/index.xhtml

BONUS: adding PrimeFaces

Simply add this to the <dependencies> section of the pom.xml:

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>15.0.0</version>
            <classifier>jakarta</classifier>
        </dependency>

And update the index.xhtml as follows:

<!DOCTYPE html>
<html lang="en"
    xmlns:f="jakarta.faces.core"
    xmlns:h="jakarta.faces.html"
    xmlns:p="primefaces"
>
    <h:head>
        <title>Hello!</title>
    </h:head>
    <h:body>
        <h1>Hello!</h1>
        <h:form>
            <p:outputLabel for="input" value="Type something: " />
            <p:inputText id="input" value="#{exampleBacking.input}" />
            <p:commandButton value="Submit" action="#{exampleBacking.submit}" update=":output" />
        </h:form>
        <h:outputText id="output" value="#{exampleBacking.output}" />
    </h:body>
</html>

That's all! Now re-execute the previously instructed build-and-run commands.

Thursday, November 23, 2023

Using OmniFaces CDI @ViewScoped with unload/destroy in a Spring Boot project

Introduction

While working on a Spring Boot based Faces project having memory issues, one of the solutions is to migrate the existing @Scope("view") beans and/or @SessionScope beans disguised as view scoped beans to use OmniFaces @ViewScoped instead, so that they get destroyed immediately when the webpage unloads and hereby also immediately frees up memory occuppied by the managed bean state as well as the Faces view state instead of basically having them to accumulate during the rest of the HTTP session.

Install JoinFaces in any case

JoinFaces is a great library for easily integrating Jakarta Faces in a Spring Boot project. However it unfortunately only supports using the standard Faces view scope @jakarta.faces.view.ViewScoped on a Spring managed bean. On the other hand, though, JoinFaces is already kind of the standard approach in order to effortlessly be able to use Jakarta Faces, Jakarta CDI and OmniFaces (and PrimeFaces, of course) in a Spring Boot project. It really takes away a lot of potential boilerplate in order to properly configure them in a Spring Boot based project. It's a matter of adding the following dependency (in Maven flavor) when you're already on Spring Boot 3.x or newer:

<dependency>
    <groupId>org.joinfaces</groupId>
    <artifactId>omnifaces-spring-boot-starter</artifactId>
    <version>5.x.x</version>
</dependency>

Or when you're still on Spring Boot 2.x:

<dependency>
    <groupId>org.joinfaces</groupId>
    <artifactId>omnifaces3-spring-boot-starter</artifactId>
    <version>4.x.x</version>
</dependency>

Getting OmniFaces @ViewScoped to work

One way would be to create a custom Spring Scope for this and port all the existing logic behind OmniFaces @ViewScoped over there, including the auto-inclusion of the unload script. However this seems to be unnecessary (not DRY) and brittle (sensitive to breaking when something incompatibly changes in the original OmniFaces @ViewScoped implementation).

Another way would be to just use a CDI managed bean instead of a Spring managed bean. Thanks to JoinFaces, CDI is readily available. However, the project already has a lot of existing Spring managed beans/services/repositories which couldn't be injected in a CDI managed bean via CDI's own @Inject. So they had to be injectable in a CDI managed bean in some way, without the need to convert these Spring managed beans to CDI managed beans and possibly losing any Spring-induced advantages/features on them and then requiring us to unnecessarily rewrite/migrate yet another bunch of code.

The idea (with help of Arjan Tijms) is to autodetect fields annotated with Spring-specific @Autowired in a CDI managed bean and simply let CDI fetch it from Spring context while injecting. This can be done with help of a CDI Extension. The major advantage is that we can then fully leverage to the original implementation of the CDI scope, including all of its originally intended behavior and features. In other words, we'll with a special CDI Extension be able to use @Named beans with @Autowired properties. This way we can transparently use OmniFaces @ViewScoped or any other CDI-specific scope without the need to copy/rewrite it.

Activate CDI

To activate CDI in a Spring Boot project after installing JoinFaces, which by default uses the Weld implementation, simply add a beans.xml file to the src/main/resources/META-INF folder of the Spring Boot project:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="https://jakarta.ee/xml/ns/jakartaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_4_0.xsd"
    version="4.0" bean-discovery-mode="annotated">
</beans>

Or when you're still on Spring Boot 2.x:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
    version="2.0" bean-discovery-mode="annotated">
</beans>

Note that this doesn't affect any existing Spring managed bean configurations. By default, they still have higher precedence. Moreover, the key configuration is explicitly setting CDI bean discovery mode to annotated so that CDI only tries to scan for beans with CDI's own bean defining annotations.

Also note that when running the Spring Boot application as a (fat) JAR file, the beans.xml needs to be located in BOOT-INF/classes/META-INF folder of the generated JAR file, not in the root META-INF folder containing web resources.

Instruct Spring to ignore CDI managed beans

We need to explicitly instruct Spring to ignore CDI managed beans annotated by @Named. Otherwise the Spring bean management facility may still have higher precedence to find and manage them, particularly if they are in the same package which is covered by @ComponentScan. This can be achieved by adding excludeFilters=@Filter(Named.class) to the @ComponentScan annotation on your Spring @Configuration class.

@Configuration
@ComponentScan(basePackages = YourSpringConfiguration.BEANS_PACKAGE, excludeFilters = @Filter(Named.class))
public class YourSpringConfiguration implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    public static final String BEANS_PACKAGE = "com.example.beans";

    // ...
}

Make ApplicationContext available in static context

Next step is to make sure that Spring's ApplicationContext is available in static context, so that the CDI extension can access it while trying to fetch Spring managed beans. There's namely no dedicated API for this in Spring Boot (yet?) such as Faces has with FacesContext.getCurrentInstance() and as CDI has with CDI.current().getBeanManager(). In a Spring Boot application, the canonical approach is to have a Spring managed bean implementing ApplicationContextAware. The average Spring Boot project should already have one somewhere, but in case yours doesn't seem to have one, then you can add one as follows:

@Component
public class Spring implements ApplicationContextAware {
 
    private static ApplicationContext context;
 
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }
 
    public static ApplicationContext getContext() {
        return context;
    }
}

Create CDI extension

Now we can create the CDI extension which autodetects fields annotated with Spring's @Autowired in CDI managed beans annotated with @Named and makes sure that these fields are injected with beans obtained from Spring context.

public class SpringAutowiredExtension implements Extension {

    private Map<Class<?>, String> autowiredFields = new ConcurrentHashMap<>();

    public <T> void processAnnotatedType(@Observes @WithAnnotations(Named.class) ProcessAnnotatedType<T> processAnnotatedType, BeanManager beanManager) {
        Class<T> beanClass = processAnnotatedType.getAnnotatedType().getJavaClass();

        if (!beanClass.getPackage().getName().startsWith(YourSpringConfiguration.BEANS_PACKAGE)) {
            return; // This should filter out any CDI managed beans provided by e.g. Faces and OmniFaces themselves.
        }

        processAnnotatedType.configureAnnotatedType()
            .filterFields(field -> field.isAnnotationPresent(Autowired.class))
            .forEach(this::registerAutowiredField);
    }

    private void registerAutowiredField(AnnotatedFieldConfigurator<?> fieldConfigurator) {
        fieldConfigurator.add(InjectLiteral.INSTANCE);
        Field field = fieldConfigurator.getAnnotated().getJavaMember();
        autowiredFields.put(field.getType(), field.getName());
    }

    public void afterBeanDiscovery(@Observes AfterBeanDiscovery event) {
        autowiredFields.entrySet().forEach(autowiredField -> injectBeanViaSpringContext(event, autowiredField.getKey(), autowiredField.getValue()));
    }

    private static void injectBeanViaSpringContext(AfterBeanDiscovery event, Class<?> type, String name) {
        event.addBean().addType(type).createWith(ignoreCdiContext -> getBeanFromSpringContext(type, name));
    }

    private static Object getBeanFromSpringContext(Class<?> type, String name) {
        try {
            try {
                return Spring.getContext().getBean(type);
            }
            catch (NoUniqueBeanDefinitionException ignore) {
                return Spring.getContext().getBean(name);
            }
        }
        catch (Exception e) {
            throw new IllegalStateException("Cannot get bean from Spring context", e);
        }
    }
}

Register CDI extension

In order to get it to run, create a file with the exact name jakarta.enterprise.inject.spi.Extension in the src/main/resources/META-INF/services folder of the Spring Boot project and add a line to it representing the FQN of the CDI extension:

com.example.cdi.SpringAutowiredExtension

When you're still on Spring Boot 2.x, then the file should be named javax.enterprise.inject.spi.Extension

To confirm, when running the Spring Boot application as a (fat) JAR file, this file needs to be located in BOOT-INF/classes/META-INF/services folder of the generated JAR file.

Profit

That's basically all! You should now be able to use CDI managed beans with OmniFaces @ViewScoped and still therein have Spring managed beans at your availability via @Autowired.

@Named
@ViewScoped
public class YourViewScopedBean implements Serializable {
 
    private static final long serialVersionUID = 1L;

    @Autowired
    private SomeSpringComponent someSpringComponent;

    @PostConstruct
    public void init() {
        // SomeSpringComponent should be readily available at this point.
        // This is the key task of the CDI extension.
    }
 
    @PreDestroy
    public void destroy() {
        // This should be correctly invoked on page unload.
        // This is the key advantage over standard Faces @ViewScoped annotation.
    }
}