When you create a new instance of ApplicationContext (no matter what type), you basically create new instances of each bean configured in this ApplicationContext . This is good the first time, it may work the second, and depending on the number of beans, then the beans type will crash after that. Since the context will never be destroyed (until the application crashes and restarts), you will encounter possible memory problems, performance problems, strange transaction problems, etc.
The general rule is to never construct a new instance of ApplicationContext , but use dependency injection instead.
If you really want access to ApplicationContext put a field of this type in your controller and put @Autowired on it.
@Controller public class MyController { @Autowired private ApplicationContext ctx; β¦. }
Then you can search for the bean that you need in this method. This can be convenient if you use ApplicationContext as a factory for your beans. If you need all the beans, then you just need to enter a bean.
@Controller public class MyController { @Autowired private MappingFileGenerator mfg ; β¦. }
Spring will now introduce the MappingFileGenerator , and it is available for use in your methods. There is no need to create a new instance of ApplicationContext .
See the Spring Reference Guide for more information.
source share