IOC(控制反转) 、DI(依赖注入)这两个概念 @Repository 存储层 @Service 服务层 @Controller 控制层 @Component 与上三个一致 @Autowired 声明类型 @Qualifier 声明名称与Autowired 并列使用 @Resource 既可以使用类型有可以使用名称
--实例一 use-default-filters="false":表示不适用默认的filter,自己配置 context:include-filter:只扫描那些 注解为:Controller 别的不扫描 <context:component-scan base-package="com.atguigu" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> 实例2 下面的配置 context:exclude-filter:不扫描那些 注解为:Controller 扫描 <context:component-scan base-package="com.atguigu" > <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
<!--开启组件扫描 1 如果扫描多个包,多个包使用逗号隔开 2 扫描包上层目录 --> <context:component-scan base-package="com.atguigu"></context:component-scan>
需要的jar包:
1.dao层创建接口以及dao层接口的实现类
public interface ChaoDao { public void add(); }
@Repository //dao层使用的注解 //如果没有value 那么默认就是类的首字母小写:chaoService public class ChaoDaoImpl implements ChaoDao{ @Override public void add() { System.out.println("ChaoDaoImpl.add"); } }
2.service层
@Service//如果没有value 那么默认就是类的首字母小写:chaoService public class ChaoService { ChaoDao chaoDao =new ChaoDaoImpl(); public void say(){ System.out.println("ChaoService.say."); chaoDao.add(); } }
3.全注解开发类
/*@Configuration //作为配置类,替代 xml 配置文件 @ComponentScan(basePackages = {"com.atguigu"}) 扫描路径 */ @Configuration @ComponentScan(basePackages = {"com.atguigu"}) public class SpingConfig { }
4测试
public class ChaoTest { @Test //完全使用注解开发 public void test(){ //通过配置类 SpingConfig 获取注解扫描路径 ApplicationContext context=new AnnotationConfigApplicationContext(SpingConfig.class); //获取实例对象 ChaoService chaoService = context.getBean("chaoService", ChaoService.class); //执行方法 chaoService.say(); } @Test //使用xml 配置文件注解开发,zhujiebean.xml文件存放于src目录下 public void test1(){ ApplicationContext context=new ClassPathXmlApplicationContext("zhujiebean.xml"); ChaoService chaoService = context.getBean("chaoService", ChaoService.class); chaoService.say(); } }