spring注解配置

一般的spring的配置都是在XML文件里配置,spring2.5之后,spring也支持注解配置。

 

1、applicaltionContext.xml

 

 

2、model层bean的配置

 

package com.beckham.model; import org.springframework.stereotype.Repository; //注解 @Repository("user") public class User { private String username ; private String sex ; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }  

 

3、controller层bean的配置

 

package com.beckham.daoimp; import org.springframework.stereotype.Controller; import com.beckham.dao.UserDAO; import com.beckham.model.User; //注解 @Controller("userDAO") public class UserDAOImp implements UserDAO { public void add(User user) { System.out.println(user.getUsername()); System.out.println(user.getSex()); } }  

 

3、service层的bean的配置

 

package com.beckham.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.beckham.dao.UserDAO; import com.beckham.model.User; //注解 @Service("userService") public class UserService { //setter注入接口、面向接口编程 private UserDAO userdao ; public void add(User user){ userdao.add(user) ; } public UserDAO getUserdao() { return userdao; } //注解 @Resource(name="userDAO") public void setUserdao(UserDAO userdao) { this.userdao = userdao; } }  

 

4、测试类

package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.beckham.model.User; import com.beckham.service.UserService; public class SpringTest { /** * beckham Dec 28, 2009 1:21:09 PM */ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService s = (UserService) ctx.getBean("userService"); User u = (User) ctx.getBean("user"); u.setSex("男"); u.setUsername("高文明"); s.add(u); } }  

 

运行结果:

高文明

你可能感兴趣的:(spring)