Spring IOC扫描器:
实例:
spring配置文件:定义一个扫描器,并设置扫描器的扫描范围为com.xxxx包下
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--自动化扫描器:设置自动化扫描的范围
作用:bean对象的统一管理,简化开发配置,提高开发效率
1、设置自动化扫描的范围(如果bean对象不在扫描范围内,即使声明了注解,也不会被实例化)
2、在需要被实例化的javaBean的类上添加指定的注解(注解声明在类级别),**bean对象的id属性默认的是类名的首字母小写
3、Dao层:@Repository,Service层:@Service,Controller层:@Controller,任意类:@Component
注意:开发过程中建议按照规则声明注解
-->
<context:component-scan base-package="com.xxxx"/>
</beans>
TypeController类:类中需要注入TypeService对象
@Controller
public class TypeController {
@Autowired
private TypeService typeService;
public void test(){
System.out.println("TypeController Test...");
typeService.test();
}
}
TypeService类:类中需要注入TypeDao对象
@Service
public class TypeService {
@Resource
private TypeDao typeDao;
public void test(){
System.out.println("TypeService Test...");
typeDao.test();
}
}
TypeDao类:
@Repository
public class TypeDao {
public void test(){
System.out.println("TypeDao Test...");
}
}
测试类:
public class App02
{
public static void main( String[] args )
{
ApplicationContext ac = new ClassPathXmlApplicationContext("spring02.xml");
TypeDao typeDao = (TypeDao) ac.getBean("typeDao");
typeDao.test();
}
}