1、创建一个配置文件applicationAutoContext.xml
点击查看代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<!--通过注解依赖注入-->
<context:annotation-config></context:annotation-config>
<!--自动扫描包-->
<context:component-scan base-package="com.bh"></context:component-scan>
</beans>
点击查看代码
package com.bh.service;
import org.springframework.stereotype.Service;
@Service
public class DeptService3 {
public void test(){
System.out.println("DeptService3 start=========");
System.out.println("DeptService3 end=========");
}
}
点击查看代码
package com.bh.controller;
import com.bh.service.DeptService3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
//@Controller(value = "deptcontroller")//可以定义一个id
public class DeptController {
@Autowired
DeptService3 deptService3;
public void test(){
System.out.println("controller start====");
deptService3.test();
System.out.println("end start====");
}
}
点击查看代码
package com.bh.test;
import com.bh.controller.DeptController;
import com.bh.dao.StudentDAO;
import com.bh.service.DeptService3;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test3 {
public static void main(String[] args) {
System.out.println("start=======");
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationAutoContext.xml");
DeptController bean = ac.getBean(DeptController.class);
bean.test();
//获取controller层注解定义的id(一般不用)
// DeptController deptcontroller = (DeptController) ac.getBean("deptcontroller");
//deptcontroller.test();
DeptService3 bean = ac.getBean(DeptService3.class);
bean.test();
StudentDAO bean = ac.getBean(StudentDAO.class);
bean.test();
System.out.println("end=======");
}
}