admin 管理员组

文章数量: 1087678

Spring5框架 IOC 注解练习

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{@Overridepublic 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();}
}

本文标签: Spring5框架 IOC 注解练习