/java/

Spring @Autowired

2013-01-13 19:27:02

1. Post Object

package pl.btbw.entity;

public class Post {

    String name = null;
    String desc = null;

    public void setName(String name){
        this.name = name;
    }
    public void setDesc(String desc){
        this.desc = desc;
    }
    public String getName(){
        return this.name;
    }
    public String getDesc(){
        return this.desc;
    }
}

2. Configuration xml

...

<mvc:annotation-driven></mvc:annotation-driven>

...

<bean class='"pl.btbw.entity.Post"' id='"PostBean"'>
<property ipsum&quot;="" name='"name"' value='"Lorem'></property>
<property adipiscing="" amet,="" consectetur="" dolor="" elit.&quot;="" ipsum="" name='"desc"' sit="" value='"Lorem'></property>
</bean>

...

3. Controller 1

@Controller
@RequestMapping(value="/basic")
public class BasicController {

    @Autowired
    private Post post;

    @RequestMapping(value="/", method= RequestMethod.GET)
    public String index(ModelMap model) {
        if(post != null){
            model.addAttribute("post", post);
        }else{
            model.addAttribute("post", null);
        }
        post.setName("Suspendisse");
        post.setDesc("Suspendisse at placerat justo. Aliquam leo velit, commodo at sagittis non.");
        return "basic/index";
    }
}

4. Controller 2

@Controller
public class HomeController {

    @Autowired
    private Post post;

    @RequestMapping(value="/", method= RequestMethod.GET)
    public String index(ModelMap model) {
        if(post != null){
            model.addAttribute("post", post);
        }else{
            model.addAttribute("post", null);
        }
        return "index";
    }
}

5. View


<body>
<p>${post.name}</p>
<p>${post.desc}</p>
</body>