spring IOC配置文件方式和注解方式实现

1.Spring:轻量级控制反转(IOC)和面向切面编程(AOP)的容器框架

思想:高内聚,低耦合

1.1 基础体系结构

核心容器:beans、core等

AOP:面向切面编程

数据访问/集成:JDBC、 ORM

网络:Web

仪器仪表:jsp等视图页面

测试:Test

1.2 核心部分

(1)控制反转(IOC):对象的创建和维护交由spring容器,实现更好的扩展性和良好可维护性

(2)面向切面编程(AOP):抽取通用功能,定义切面,消除代码冗余。需结合IOC使用。

2.IOC的配置文件方式(接口注入)

(1)创建配置文件applicationContext.xml

声明xml类型

(2)创建要注入bean类

(3)注入applicationContext.xml容器,生成id指定的bean——sealImageDao,此bean将由spring管理其生命周期及其和其它对象的关系

容器中id指定的bean值可随意写,class对应的类路径必须正确。

注:property标签中的name值必须在类中有setter,否则无法正常启动。

(4)获取applicationContext.xml容器中bean的方式

a.通过ClassPathXmlApplicationContext对象读取配置文件获取:

    ClassPathXmlApplicationContext applicationContext1 = new ClassPathXmlApplicationContext("applicationContext.xml");

    SealImageDaoImpl sd=applicationContext1.getBean("sealImageDao", SealImageDaoImpl.class);

之后可通过sd变量调用SealImageDaoImpl中的属性或方法

b.通过实现ApplicationContextAware接口获取:

此接口会在加载时自动执行setApplicationContext(ApplicationContext arg0)

可设置静态ApplicationContext类型变量接收arg0,如下图:

注:1.使用b中方式获取bean时此处用的注解方式@Component,要在容器中加入扫描此工具类所在包(此处容器不是applicationContext.xml,分开写的另一个容器)

此处扫描时要将bean所在容器一起导入同时加载,否则无法获取到bean

2.当没有@Component时必须在容器中(applicationContext.xml)加载此工具类(不是扫描,是设置bean)

获取bean:

SealImageDaoImpl sd=ApplicationContext_init.getContext().getBean("sealImageDao", SealImageDaoImpl.class);

 

3.注解方式

       注解写法:@注解名称(属性名称=属性值)

  注解使用在类上面,方法上面和属性上面

3.1 创建applicationContext.xml容器并引入约束

3.2 一些注解类型说明

@Component:元注解,带此注解的类看做是一个组件,可以注解其他类注解,可设置参数value指定bean,如:@Component(value="emailVo"),等同于配置文件方式:<bean id="emailVo" class="...">,如不指定bean名称则默认为类首字母小写的类名:EmailVo(类名)—>emailVo(bean名),下同

@Repository:组合注解(组合了@Component注解),应用在dao层(数据访问层),可设置value指定bean

@Service:组合注解(组合了@Component注解),应用在service层(业务逻辑层),可设置value指定bean

@Controller:组合注解(组合了@Component注解),应用在MVC层(控制层),可设置value指定bean

@Resource:按名称装配注入,需指定name值,如:

@Resource(name="emailVo")//name为配置文件中的id或加了@Component注解的类指定的value值(不指定,则类名:EmailVo)
 private EmailVo emailVo;

@Autowired:按类型装配注入,无参,根据被注解的属性的类型来确定类名;

可结合@Qualifier注解按照名称装配注入,用于一个接口衍生多个子类,确定用哪个子类,如:

@RequestMapping:用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径

说明:@Resource和@Autowired可消除配置文件中bean的setter方法

3.3 配置文件扫描注解类

注:所有用到注解功能的类都必须扫描到,否则注解无效。

2.4 应用(仅展示控制层的注解)

参考:

https://www.cnblogs.com/fullstack-kevin/p/8764047.html

https://blog.csdn.net/ss_aa_aa/article/details/78093116

https://www.cnblogs.com/xinruyi/p/11160933.html

https://www.cnblogs.com/cocoxu1992/p/10554889.html

https://blog.csdn.net/qq_36567005/article/details/80611139

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值