1

I have autowired ApplicationContext in my RestController class as I needed to create a prototyped bean for each of the request received.

To create the bean I tried context.getBean(xx) but context has not getBean() method listed. Is there a way that I can get beans of the prototyped class in my RestController class. I am running this application as Spring boot.

sample code is here:

@RestController
@RequestMapping("/Restcompare")
public class CompareService {


    @Autowired
    private ApplicationContext context;

    private Comparator comparator;

    @RequestMapping("/compare")
    public String vcompare(@RequestParam(value="pre", defaultValue="") 
    String pre, @RequestParam(value="post", defaultValue="") String post){


        comparator = context.getBean(Comparator.class);  //Error here
    }
}

Update:

Solution: Somehow IDE imported a different ApplicationContext other than the Spring framework's. Correcting the import to org.springframework.context.ApplicationContext resolved the issue.

Bharath Reddy
  • 301
  • 2
  • 4
  • 15

2 Answers2

6

Somehow IDE imported a different ApplicationContext other than the Spring framework's. Correcting the import to org.springframework.context.ApplicationContext resolved the issue.

Bharath Reddy
  • 301
  • 2
  • 4
  • 15
1

You can inject your bean with @Autowired, like this:

@Autowired
private Comparator comparator;
Felipe Mariano
  • 564
  • 5
  • 8
  • This won't work as the comparator bean in compareService class is created only once. The correct way is to create prototyped bean using context only. The problem I had is spring imported a different ApplicationContext other than spring's. Correcting the import to org.springframework.context.ApplicationContext resolved the issue. Thanks for responding. – Bharath Reddy Oct 26 '17 at 17:44
  • Oh, no problem! – Felipe Mariano Oct 26 '17 at 18:01