Amol Ghotankar
Amol Ghotankar

Reputation: 2094

Spring Injection in JSP

I have a jsp page which needs a java code.

This java code inside jsp needs a service class.

Now my service class is java gets created using spring DI and DAO & other things are injected in service class using Spring.

But when i want to use it in jsp, how should I ask spring to provide me the object of service inside jsp?

JSP -> Java Code -> Service -> DAO

I am using struts2 & spring DI as frameworks.

Upvotes: 2

Views: 4670

Answers (2)

Alexey Berezkin
Alexey Berezkin

Reputation: 1543

You can create a class that is Spring-managed and application context aware. This class will provide Spring bean via static methods from anywhere in your code.

@Service
public class SpringBeansProvider implements ApplicationContextAware {

    static private ApplicationContext applicationContext;

    public static <T> T getBean(String beanName, Class<T> type) {
        return applicationContext.getBean(beanName, type);
    }

    @Override
    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

}

From anywhere in your code, use SpringBeansProvider.getBean("myBean", MyBean.class). Yes, this breaks down a concept of beans injection and mixes up static and non-static methods usage, but such kind of task always cause those unfair things.

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160170

You don't inject into JSP pages; you inject into the action class and access using normal S2 mechanisms.

Upvotes: 0

Related Questions