Wednesday, 7 February 2018

How to use beans with annotations ?


Spring container manages all the beans specified in XML config or defined with annotations like, @component, @Resource, @Bean etc.

@Component : Used to define beans (managed by Spring container)
public abstract class Shape {
    abstract void draw();
}


@Component
public class Arc extends Shape {
    public void draw() {
        System.out.println("Draw an Arc.....");
    }

}

By default, bean ID / name will be the same as class name.
Best practice is to use bean ID / name with every bean with @Component :
@Component("arc")
public class Arc extends Shape { ... }


// Get bean objects from Spring container 
Shape arcA = ctx.getBean(Arc.class);
System.out.println("Arc object : " + arcA);
Shape arcB = ctx.getBean(Arc.class);
System.out.println("Arc object : " + arcB);

Both will print the same object, because by default Spring beans are singleton.


@Scope : Used to define bean scope
In order to create different objects every time you can define scope = prototype

@Scope("prototype")
@Component

public class Arc extends Shape { ... }

Best practice is to use Singleton beans, until there is no data maintained inside the beans.
If outer class is singleton and inner one is prototype, there is no sense making inner class prototype, as there will be always a single object outside.


@Bean : Used to define another object as Spring bean
When you create beans using "new" keyword, it will not be managed by Spring container.
Still you can register this created object using @bean and inject at other places.
@Bean
public Shape arc() {
   return new Arc();
}



No comments:

Post a Comment

Note: only a member of this blog may post a comment.