为了提高编程效率,spring矿建对javaBean对象进行了统一的管理,可以通过扫描某个目录,帮助我们自动实例化对象。
@Repository
public class TypeDao {
public void test(){
System.out.println("TypeDao.test");
}
}
@Service
public class TypeService {
@Resource
TypeDao typeDao;
public void test(){
System.out.println("TypeService.test");
typeDao.test();
}
}
@Controller
public class TypeController {
@Resource
TypeService typeService;
public void test(){
System.out.println("TypeController.test");
typeService.test();
}
}
Spring IOC 扫描器
作用:bean对象统一进行管理,简化开发配置,提高开发效率
1、设置自动化扫描的范围
如果bean对象未在指定包范围,即使声明了注解,也无法实例化
2、使用指定的注解(声明在类级别) bean对象的id属性默认是 类的首字母小写
Dao层:
@Repository
Service层:
@Service
Controller层:
@Controller
任意类:
@Component
注:开发过程中建议按照指定规则声明注解
public class TypeControllerTest {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring2.xml");
// TypeService typeService= (TypeService) applicationContext.getBean("typeService");
// typeService.test();
TypeController typeController= (TypeController) applicationContext.getBean("typeController");
typeController.test();
}
}
配置文件很干净了,但是也需要引入spring-context,和官网上的还是有点区别,这里也不需要 context:annotation-config</context:annotation-config>(自动注入时候用的),也封装在里面了
<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">
<!--设置扫描范围-->
<context:component-scan base-package="com.zks"/>
</beans>