Heschoon
Heschoon

Reputation: 3019

How to use beans instead of static classes in facelets taglibs?

Is it possible to use methods of spring beans instead of static methods when defining tag-lib functions?

At the moment the application only uses static methods of abstract classes:

<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib
        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/web-facelettaglibrary_2_2.xsd"
        version="2.2">
    <namespace>http://my/security/facelets/tags</namespace>

    <function>
        <function-name>isRegion</function-name>
        <function-class>my.NovaFaceletsAuthorizeTagUtils</function-class>
        <function-signature>boolean isRegion()</function-signature>
    </function>

Upvotes: 0

Views: 56

Answers (1)

meriton
meriton

Reputation: 70564

No, but you can delegate to bean methods. For instance, like this:

public static boolean isRegion() {
    getCurrentApplicationContext().getBean(RegionService.class).isRegion();
}

There are various approaches for getting the current ApplicationContext, depending on how you're bootstrapping it, and how many ApplicationContext you have. For an overview of relevant techniques, see:

In simple cases, where the bean is application scoped and doesn't have AOP advice (in particular, no @Transactional), it might be easier to put the bean itself into a static field:

@Component
public class RegionService {
    private static RegionService instance;

    public RegionService() {
        instance = this;
    }

    public static RegionService getInstance() {
        return instance;
    }
}

so you can use RegionService.getInstance() to access the bean from anywhere.

Upvotes: 1

Related Questions