Using the Spring Container for new instances

One of the most common mistakes when using  Spring IOC is using the new()  to create a new instance. If you instantiate a bean this way it won’t be picked up the Spring container and you lose all the magic that comes with IOC.

  1. When you create the class make sure you use the prototype scope
    @Component
    @Scope(value=”prototype”)
    Class MyClass {
    ……..
  2. Autowire the context into the bean
    @Autowired
    private ApplicationContext context;
  3. Instantiate the bean in your code
    MyNewClass myObject = context.getBean(MyNewClass.class)

And you’re done. The fact that we’re still creating beans using factories can easily be forgotten when we are using annotations. However you can still do things the old way.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s