Arsen Alexanyan
Arsen Alexanyan

Reputation: 3141

Reuse spring service controller functionality inside another controller

I have service controller which functionality I would like to reuse in another controller. Here is my service controller

@Controller
@Service
@Scope("session")
public class Controller1{
...
}

Here is my second controller

 @Controller
 public class Controller2 {
     @Autowired
     private Controller1 adminController;
     ...
 }

But I'm getting exception which says:

Error creating bean with name 'adminController': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton;

I think that this is because Controler1 is session-scoped bean and Controller2 is application. How can I reuse then Controller1 functionality inside Controller2? Thanks.

Upvotes: 0

Views: 1444

Answers (3)

Debojit Saikia
Debojit Saikia

Reputation: 10632

Both of these annotations @Controller and @Service serve as a specialization of @Component, which allows the implementation classes to be autodetected through classpath scanning. And @Controller is typically used in combination with annotated handler methods to handle http requests. So you don't have to use @Controller and @Service on the same class. You can safely remove @Service.

Now if you want to inject an HTTP session scoped bean into another bean, you must inject an AOP proxy in place of the scoped bean.

That is, you need to inject a proxy object that exposes the same public interface as the scoped object but that can also retrieve the real, target object from the relevant scope (in this scenario, an HTTP session) and delegate method calls onto the real object. So, in order to make it work, change the @Scope annotation of Controller1 to this:

@Controller
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Controller1{
...
}

Upvotes: 1

karci10
karci10

Reputation: 375

you can use aop:scoped-proxy in your xml config file for controller1

 <bean id="controller1" class="...Controller1" scope="session">
    <aop:scoped-proxy />
 </bean>

look at spring scoped proxy bean

Upvotes: 1

Thomas
Thomas

Reputation: 1420

It depends of what you mean by functionnality but if you want to share a method in both controller, why not defining an abstract parent class defining this method and extends both controllers from this parent ?

Upvotes: 0

Related Questions