【核心核心】4.Spring【IOC】注解方式
2024-10-07 23:46:50
1.导入jar包
2.创建对应的类
public interface HelloService { public void sayHello(); }
/** * @Component(value="helloService") 相当于 <bean id="helloService" class="com.spring.demo1.HelloSeviceImpl"/> * @author NEWHOM * */ @Component(value="helloService") public class HelloSeviceImpl implements HelloService { @Override public void sayHello() { // TODO Auto-generated method stub System.out.println("Hello Spring !!"); } }
3.在applicationContext.xml中引入约束
<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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> </beans>
4.在applicationContext.xml中开启组件扫描
<context:component-scan base-package="com.spring.demo1" />
5.在HelloServiceImpl上添加注解
@Component(value="helloService") 相当于 <bean id="helloService" class="com.spring.demo1.HelloSeviceImpl"/>
6.编写测试类
public class Demo1 { /** * 测试注解方式的IOC */ @Test public void m01(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloService helloService = (HelloService) ac.getBean("helloService"); helloService.sayHello(); } }
注意:
Spring中提供@Component的三个衍生注解:(功能目前来讲是一致的)
* @Controller -- 作用在WEB层
* @Service -- 作用在业务层
* @Repository -- 作用在持久层
最新文章
- 局域网内利用gitlab,jenkins自动生成gitbook并发布(nginx)
- mybatis+MySQL--CRUD
- iOS 模拟器上录制Demo视频
- #笔记#JavaScript进阶篇二
- QLabel添加图片链接
- ecshop常用语句
- 【iOS基础】NSURLConnection
- IE9 浏览器无法捕获中键事件
- SeaJS之shim插件:解决非cmd规范的插件与sea的区别
- 将Maven的Web项目部署到windows的Tomcat里
- Redis进阶实践之八Lua的Cjson在Linux下安装、使用和用C#调用Lua脚本
- Linux高级运维 第五章 Vim编辑器和恢复ext4下误删除的文件-Xmanager工具
- 漫谈hashcode
- 系统运维|SqlServer2008|数据库日志文件过大需要清理的操作攻略
- AC自动机-HDU2222-模板题
- 2017-2018-2 20165225『Java程序设计』课程 结对编程练习_四则运算
- JoyOI1940 创世纪
- information_schema系列十一
- 判断一个对象是否为真 __nonzero__ 方法和 __len__方法
- Spring boot --- Spring Oauth(三)