How to create a request scoped bean at runtime with spring

Viewed 27866

I have a spring application and want to create a bean at runtime per request to inject it into another class, just like @Producer for CDI.

My bean is just a simple POJO:

public class UserDetails {

    private String name;

    // getter / setter ... 

    public UserDetails(String name) {
        this.name = name;
    }
}

My producer class looks like this:

@Configuration
public class UserFactory {

    @Bean
    @Scope("request")
    public UserDetails createUserDetails() {
        // this method should be called on every request
        String name = SecurityContextHolder.getContext()
                        .getAuthentication().getPrincipal(); // get some user details, just an example (I am aware of Principal)

        // construct a complex user details object here
        return new UserDetails(name)
    }
}

And this is the class where the UserDetails instance should be injected:

@RestController
@RequestMapping(value = "/api/something")
public class MyResource {

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<String> getSomething(UserDetails userDetails) {
        // the userdetails should be injected here per request, some annotations missing?

        // do something
    }
}

The problem is that Spring complains at runtime about no default constructor (of course).

Failed to instantiate [UserDetails]: No default constructor found

But this is intended and I want to call my own factory to let it handle the Instantiation.

How can I achieve this? Why is UserFactory never called?

3 Answers
Related