Spring整理笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hlw521hxq/article/details/82972366

Spring框架搭建

jar导入

  • spring-core:依赖注入IOC与DI的最基本实现

  • spring-beans:Bean工厂与bean的装配

  • spring-context:spring的context上下文即IoC容器

  • spring-context-support

  • spring-expression:spring表达式语言

配置SpringConfig.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    
</beans>

Bean的装配

  • 基于xml配置的装配

    Property 属性解释
    class 指定bean对应类的全路径
    name name是bean对应对象的一个标识
    scope 执行bean对象创建模式和生命周期
    id id是bean对象的唯一标识,不能添加特别字符
    lazy-init 是否延时加载 默认值:false
    init-method 对象初始化方法
    destroy-method 对象销毁方法
ApplicationContext app=new ClassPathXmlApplicationContext("SpringAutoScan.xml");
ApplicationContext app=new FileSystemXmlApplicationContext("SpringConfig.xml");
app.getBean("id");

创建对象的方式

  1. 无参构造

    <bean id="" class=""></bean>
  2. 静态工厂方法

    <bean id="" class="" factory-mthod=""></bean>
  3. 非静态工厂方法

    <bean id="bean1" class=""></bean>
    <bean id="" class="" factory-bean="bean1" factory-method=""></bean>
  4. 参数注入

    • set方法注入

    <property name="name" value="李四"></property>
    • 构造方法注入

    构造函数方法
    <conshuctor-org index="" value/ref-""></conshuctor-org>
    参数名
    <conshuctor-org  value/ref-"" name=""></conshuctor-org>
    类型
    当参数名相同的,用type区分
    <conshuctor-org name="" value/ref-"" type="" ></conshuctor-org>
  5. P空间命名

    1. 配置文件添加p命名空间

    2. 代码

      <bean id="" class="" p:属性名/p:属性名-ref=""></bean>
  6. 自动注入

    1. 属性autowire

      no 不自动装配
      byName id="属性名"
      byType 类型,多个同类型报错
      constructor 构造方法的参数类型与id对象的类型相同

      配置在<beans>里面,表示全局自动装配

      配置在<bean>里面,表示单个自动装配

    2. 复杂类型注入

    3. Spring表达式

      #{对象名.属性名}
    4. 基于注解

      1. SpringConfig.xml文件添加context;

      2. 添加context-scan扫描

      3. 添加注解

        类:
        @Component+("")//普通实现类:里面是id名,默认是首字母小写类全拼,以下全是
        @Repository//dao层:
        @controller//servlet层
        @Service//service层
        @Scope(scopeName="singleton/pototype")//表示是否单例模式创建对象
        属性:
        @Value("")//直接赋值
        @Autowired()//类型注入
        @Qualifier("")//解决相同类型实体类,指定实现类
        @Resource(name="")//直接指定实现类
        方法:
        @PostConstruct//初始化
        @PreDestory//销毁方法

猜你喜欢

转载自blog.csdn.net/hlw521hxq/article/details/82972366
今日推荐