Spring: How to inject a property with a non-setter method?

dependency-injection, jetty, spring

Solution

I am looking at Jetty/Tutorial/Embedding Jetty documentation. I guess you mean calling `ServletContextHandler.addServlet()`. You have few choices:

`@Configuration` (since 3.0)

My favourite approach. You can configure everything using Java!

@Configuration
public class Jetty {
    @Bean(initMethod = "start")
    public Server server() {
        Server server = new Server(8080);
        server.setHandler(context());
        return server;
    }

    @Bean
    public ServletContextHandler context() {
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.addServlet(servlet(), "/*");
        return context;
    }

    @Bean
    public ServletHolder servletHolder() {
        return new ServletHolder(helloServlet());
    }

    @Bean
    public HelloServlet helloServlet() {
        return new HelloServlet();
    }
}

Inheritance/decorating

You can inherit from or wrap original `ServletContextHandler` class to follow Java bean naming conventions. Of course it requires an extra class, but makes Jetty class Spring-friendly. You can even publish such wrapper or maybe someone already did that?

`MethodInvokingFactoryBean`

I don't like this approach as it seems too low level. Basically you create a bean that calls arbitrary method with arbitrary arguments:

<bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
 <property name="targetObject" ref="servletContextHandler"/>
 <property name="targetMethod" value="addServlet"/>
 <property name="arguments">
   <list>
     <ref bean="yourServlet"/>
   </list>
 </property>
</bean>

Problem

Is it possible to inject a property bean through a method with a signature doesn't start with `set`? Specifically, I'm trying to use Spring to configure an embedded Jetty instance and I need to be able to inject a servlet bean via an `addServlet()` method.

Original source