首页 > 编程语言 > 详细

Spring

时间:2019-07-05 20:12:33      阅读:115      评论:0      收藏:0      [点我收藏+]

使用注解配置Spring入门

 说在前面

学习基于注解的IoC配置,大家脑海里首先得有一个认知,即注解配置和xml配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。

关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯。所以这两种配置方式我们都需要掌握。

 

   基于注解配置的方式也已经逐渐代替xml。所以我们必须要掌握使用注

 配置步骤

 

注意:Eclipse需要先安装了STS插件,或者使用STS开发工具创建项目。

解的方式配置Spring

 

第一步:拷贝必备jar包到工程的lib目录。

技术分享图片

 

第二步:在类的根路径下创建一个任意名称的xml文件(不能是中文)

 

注意:基于注解整合时,Spring配置文件导入约束时需要多导入一个context名称空间下的约束

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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>

 

第三步. 创建一个服务类

创建一个测试的服务类,并且加入使用@Component注解声明该类允许注入到Spring容器

 

 第四步在spring的配置文件加入扫描注解

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">

   <!-- 声明扫描包以及子包的类。如果发现有组件注解的类,就创建对象,并加入到容器 -->
   <context:component-scan base-package="cn.zj.spring"></context:component-scan>
</beans>

 

Spring

原文:https://www.cnblogs.com/406070989senlin/p/11140417.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!