Spring基础框架搭建

Spring   轻量级 开源   集成框架

   设计图  对象的创建 和 组装    ioc    di    对象bean 的定义

   代码调用之前 之后   前后 都有  织入代码  aop  面向切面  事务处理

SpringMVC  SpringBoot    

使用 步骤 

1.导入包 和 配置文件

项目 右键--> myeclipse -->add Spring capability...    一顿下一步

定义类    applicationContext.xml 中配置

<bean  id="" class=""  >

<property name="" value="">  

注意 name 实际调用 set 方法

</bean>  节点

如何获取

ApplicationContext  acc=new ClassPathXmlApplicationContext("/applicationContext.xml");

   acc.getBean("id");

bean节点的作用域 Scope     默认是 SingleTon    单例模式

即 通过getBean 方式得到的 都是同一对象

 scope="prototype"  原型模式  每次都是新的对象

 

 

构造函数 赋值

 

getBean(id) 通过id 匹配      需要 bean节点的 id 唯一

getBean(类.class) 通过类型匹配   需要bean 节点  的类型唯一

 

// IOC  控制反转   对象的 创建 交由 spring 管理

// DI   依赖注入  对象之间的引用 赋值  交由spring 管理  

 

 

p属性   

<bean id="hlj2" class="com.pojo.Province"  p:属性="值"   p:属性-ref="beanid">

 </bean>

p 引入   

  xmlns:p="http://www.springframework.org/schema/p"

引入 其他 spring 的配置文件

<import   resource="pp.xml"/>

外部引入  导入 properties 属性文件

<context:property-placeholder   location="位置" ></ context:property-placeholder>

 

自动 注入   autowire

byName  通过 属性名称 和 bean id 的 匹配 完成自动注入

byType  通过 属性类型 和 bean 节点 的类型  匹配完成注入 但 该类型只能有一个 bean   以上都不建议使用

          

bean 对象的 生命周期

 

 类 实现 BeanPostProcessor    拦截 bean 对象的 初始化 过程

 

 

 

spring  El 表达式

   ${ } 将属性文件中的 内容 读取显示  

   #{ 值,其他bean的 属性 值 }

 

 Spring  注解  @

bean  创建  定义 获取  依赖关系  

配置  --> 零配置

@Component

@Controller   用于 定义  C 层  的bean

@Service      用于 定义  service 的bean

@Repository   用于定义 持久层   dao   

与 bean 相同含义   意义 一样  

<bean id="abc">  

使用  

1.配置 包扫描器

  <context:component-scan  base-package="基本包,包1,包2"  >

2.在类上定义 注解

@Respository(value="bean 的id ")  不写 默认 是 类名首字母小写

public  class Student{

}

 bean 之间的依赖注入

 借助于 @Autowired( require)

 

@Autowired  默认 先按 属性名称进行匹配 规则为 属性名 匹配 bean 的 id

                 如果没有 则按 类型 进行匹配

    可以 通过@Qualifier(value="abc")  指定 bean id 是 abc 的 对象 注入给course 属性

@Resource(name="abc")  默认 通过 属性名称匹配  也可按照类型匹配

扫包 的注解   <context:component-scan base-package=""></ context:component-scan>

定义bean 的 四个注解 @Component @Controller @Service @Repository

自动注入的注解

@Autowired

@Qulifier

@Resource

猜你喜欢

转载自blog.csdn.net/zhww1996/article/details/81460274
今日推荐