Spring注解开发-Bean注册
1、使用注解开发我们需要在applicationContext.xml文件中添加context标签。
在配置文件中开启注解扫描.
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="cn.niwotaxuexiba" />beans>
代码中使用@Component注解,Service层使用@Service注解.
//@Component("userService")
@Service("userService")
//
public class UserServiceImpl implements IUserService {@Value("张三")private String name;//@Autowired //默认是按照类型来进行注入//@Qualifier("userDao")@Resource(name="userDao")private IUserDAO userDao;@Overridepublic void add() {// System.out.println("userService add.." + name);userDao.add();}@Value("张三")public void setName(String name){this.name=name;}}
在spring2.5后为@Component添加了三个衍生的注解(重点)
@Repository 用于DAO层
@Service 用于service层
@Controller 用于表现层
对于我们的bean所处在的位置可以选择上述三个注解来应用,如果你的bean不明确位置,就可以使用@Component.
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
