How to make spring service class as prototype


By default spring service class comes with the singleton behaviour, I want to change service class as a prototype.

My current code is like this

import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;
    
    private String name;
    
    public void insert(String name) {
        this.name = name;
    }
}

Controller is creating one service bean and calling every time.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    private UserService userService;


    @GetMapping(value = "/user/{name}")
    @ResponseBody
    public void insertUser(@PathVariable("name") String name) {
        userService.insert(name);
    }

}

Above example, each and every request name is overriding in the service class.

1 Answer

5 years ago by

We can convert singleton to prototype for any spring bean by using @Scope on top of the class.

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

Now your code looks like this

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;

@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserService {

    @Autowired
    private UserDao userDao;
    
    private String name;
    
    public void insert(String name) {
        this.name = name;
    }
}

5 years ago by Anil