Spring and attach() method behaviour

Hello,

I’m new on Vaadin (6.8.8) and I’m trying to integrate Spring with Vaadin. I follow
this tutorial
to get annotation integration and it seems that works.

But I noticed that in some classes when I call to constructor method the dependencies aren’t injected, but if I implement attach method the dependencies are injected.

Here is a class with this problem:


@Configurable
public class HotelAvailabilityPanel extends Panel {
	
	private static String NO_IMAGE_FILE = "images/no_image.png";

	@Autowired
	private AvailabilityController controller;
	
	private MessageHelper msg;
	private MainApplication app;

	private RoomStay roomStay;
	
	public HotelAvailabilityPanel(MainApplication app, RoomStay roomStay) {
		this.roomStay = roomStay;
		this.msg = app.getMsg();
		this.app = app;
		
		//init();
	}
	
        @Override
	public void attach() {
		init();
	}
	
	private void init() {
		
		// Layout with hotel information
		HorizontalLayout hotelInfoLayout = new HorizontalLayout();
		hotelInfoLayout.setMargin(false);
		hotelInfoLayout.setSpacing(true);
		hotelInfoLayout.setSizeFull();
		
		/**
                     ...
                     some code which calls to getBestPrice()
                     ...
                **/
	}
	
	private String getBestPrice() {
		return controller.getRoomRateBestPrice(roomStay).toString() + msg.getMessage("currency1");
	}
	
}

If I call init() method inside the constructor, the controller is null, but If I call init() method inside attach() method, the controller is not null.

I think I am missing something. Why is my depencency not injected in that case? What is the attach() method approach?

Your controller gets injected using Setter-based DI. So it can’t be set in the constructor as the Object needs to be constructed before the dependencies can be injected.

Thank you! Now it works.

For completeness sake, if you are using field autowiring, you can can also tell Spring to autowire the fields before construction by specifitying preConstruction=true on the Configurable annotation - i.e. @Configurable(preConstruction = true)

(See note in
Spring Documentation
)

Cheers,

Charles