Spring中的扫描注解器
1、配置xml文件
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 扫描包中注解标注的类 -->
base-package="需要扫描的包"
<context:component-scan base-package="com.bdqn.dao,com.bdqn.service,com.bdqn.entity" />
</beans>
2.在dao中的实现类中写一个注解@Repository(“自定义别名”)
代码如下:
package com.bdqn.dao.impl;
import org.springframework.stereotype.Repository;
import com.bdqn.dao.UserDao;
@Repository("自定义别名")
public class UserDaoImpl implements UserDao{
@Override
public int add() {
System.out.println("添加成功!");
return 1;
}
}
3.服务实现类中添加注解@Service(“自定义别名”)
代码如下:
package com.bdqn.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.bdqn.dao.UserDao;
import com.bdqn.service.UserService;
@Service("自定义别名")
public class UserServiceImpl implements UserService{}
4.在服务实现类中方法添加注解
@Autowired :自动装配 ;
@Qualifier(“自定义别名”) :寻找装配对象 自定义别名–关联dao实现层中的自定义别名。
5、测试代码:
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService impl=(UserService) applicationContext.getBean("userService");---userService为@Service("自定义别名")中的自定义别名
impl.add();