28 July 2011

How to inject parameter to controller in spring 3?

Solution for Spring 3 (Annotations)

In many tutorials you can find how to add parameter to service and it looks is , it is and ...  it doesn't work when you trying apply "easy successful receipe" to controller, so shit hit the fun and you feel screwed up.

However... solution for your problem is still simply.
You need:
1)Set parameter in META-INF/context.xml
 <?xml version="1.0" encoding="UTF-8"?>
 <Context displayName="Another awsome program">
 <Parameter name=" param/naughty/url " value="http://pastor.ovh.org"/>
 (... bunch of other stuff ...) 
2) In your marvellous controller
package org.ovh.pastor.mvc.controller; 
public classAwsomeController  {
(  ... bunch of other stuff ...) 
private @Value("${param/naughty/url}") String doggyWebsite;  
 public void setDoggyWebsite ( String doggyWebsite ) {
this. doggyWebsite = doggyWebsite ;
(  ... bunch of other stuff ...)   

 Little explanation of most important line:

  private @Value("${param/naughty/url}") String doggyWebsite;

where :
  •  private  - modifier
  • @value - is a lovely annotation that contain information where is parameter 
  • String -  data type 
  •  doggyWebsite  - vairable name

Hope , it helps . Keep smiling and pray that someday spring will be easier , better explained by examples.