简体   繁体   中英

Force superclasses to include a no-argument constructor

Regarding Spring Controllers; when a Constructor is included, a no-arg constructor must be included as well otherwise a 'NoSuchBeanDefinitionException' occurs. This message is very vague and caused me some headache.

We currently have an abstract controller class which most of our controllers extend from. It appeared that when my controller extended this class (Which has a 1 arg constructor), suddenly I received the 'NoSuchBeanDefinitionException'.

I'd like to help future developers (or even myself in the future) by forcing anyone extending the abstract controller to include a no-arg constructor. Is this possible?

Edit, adding code for clarity

Here's the class most of the controllers extend from, it includes a few helper methods:

public class AbstractController
{
     private String sessionName;
     // other attributes / final variables

     public AbstractController(String sessionName)
     {
         this.sessionName = sessionName;
     }

     public boolean isCommandInSession(HttpSession session)
     {
         return session.getAttribute(sessionName) != null;
     }

     // Other helper methods which include use of 'sessionName'
}

Example of one of many controllers, which works fine. Without the default constructor, or with only overriding the 1 arg constructor this controller will fail with 'NoSuchBeanDefinitionException'

@Controller
@SessionAttributes(SomeController.COMMAND)
@RequestMapping(SomeController.URL)
public class SomeController extends AbstractController
{
    private String command = "someUniqueSessionName";

    public SomeController()
    {
        super(COMMAND);
    }
}

You should refactor as below:

public class AbstractController
{    
     public boolean isCommandInSession(HttpSession session)
     {
         return session.getAttribute(getSessionName()) != null;
     }

     abstract String getSessionName();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM