自学spring的第三天

bean配置

一、bean的作用域

  • bean的四大作用域

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s7fw8Ngi-1631536006438)(assets/image-20210910102642610.png)]

  • singleton

    • 默认的配置方式

    • 每次getBean同一个id,获取同一个实例对象

  • prototype

    • 每次调用getBean方法,都会返回一个新的实例对象
  • request

    • 每次请求,都会产生一个新的bean实例对象
  • session

    • 每次会话都会产生新的bean实例对象

二、导入beans.xml文件

  • 在原先的bean xml文件导入其它的bean xml文件,其它归属同一个ioc容器管理

  • 使用import标签使用

        <import resource="beans_import.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"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <import resource="beans_import.xml" />
    
        <bean id="boss" class="com.gec.bean.Boss" >
    
            <property name="bossName" value="#{'马老板'}" />
            <property name="car" ref="car"/>
    
        </bean>
    
    
    </beans>
    

三、FactoryBean类

1、简介

  • 此工厂类,创建bean对象,此FactoryBean是Spring框架提供接口,可以自定义工厂bean对象

2、分析FactoryBean接口

  • T getObject

    • 产生bean对象
  • getObjectType

    • bean对象的类型
  • isSingleton

    • 指明bean的作用域

3、如何使用FactoryBean接口

  • 需求

    • 注入一个字符串属性,字符串属性格式:

      品牌名,价格
      
  • 如何使用

    • 实现FactoryBean的接口

      package com.gec.factory;
      
      import com.gec.bean.Car;
      import org.springframework.beans.factory.FactoryBean;
      
      public class CarFactoryBean implements FactoryBean<Car> {
      
          private String carprop;
      
          public void setCarprop(String carprop) {
              this.carprop = carprop;
          }
      
          /*
          * 产生bean对象
          * */
          @Override
          public Car getObject() throws Exception {
      
              //将属性字符串拆解到数组
              String props[]=carprop.split(",");
      
              Car c=new Car();
              c.setBrand(props[0]);
              c.setPrice(Double.parseDouble(props[1]));
      
              return c;
          }
      
          /*
          * bean的对象类型
          * */
          @Override
          public Class<?> getObjectType() {
              return Car.class;
          }
      
          /*
          * 指明作用域
          * */
          @Override
          public boolean isSingleton() {
              return true;
          }
      }
      
      
    • 配置FactoryBean

      <?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">
      
          <!--
              访问此bean对象,并不是访问CarFactoryBean对象,而是访问工厂bean所产生的bean对象
          -->
          <bean id="carFactoryBean" class="com.gec.factory.CarFactoryBean">
              <property name="carprop" value="特斯拉,1000000.00" />
          </bean>
      
      </beans>
      

四、如何注入外部文件的数据

1、简介

  • 将外部文件的数据注入到bean对象属性里面

2、用法

  • 依赖context标签下的property-placeholder属性

  • 定义一个properties文件

    url=jdbc:mysql://localhost:3306/hibernate_db
    username=root
    password=1111
    
  • 定义一个Dbuitls类

    package com.gec.bean;
    
    public class Dbuils {
    
        private String url;
        private String username;
        private String password;
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        @Override
        public String toString() {
            return "Dbuils{" +
                    "url='" + url + '\'' +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }
    }
    
    
  • 定义beans.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"
           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 https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--导入外部配置文件-->
        <context:property-placeholder location="db.properties" />
    
        <bean id="dbuils" class="com.gec.bean.Dbuils">
            <property name="url" value="${url}" />
            <property name="username" value="${username}" />
            <property name="password" value="${password}" />
        </bean>
    
    </beans>
    

五、如何通过注解配置bean对象

1、四大注解

  • @Component

    • 此注解是标注bean对象的基本注解
  • @Repository

    • 此注解是作用于DAO的bean对象配置
  • @Service

    • 此注解是作用于Service层的bean对象配置
  • @Controller

    • 此注解是作用于控制器的bean对象配置
  • 注意

    • @Repository、@Service、@Controller都属于@Component的一种

2、如何使用上述注解配置成bean

  • 在bean类添加上述注解

    • @Component、 @Repository、 @Service、 @Controller
  • 在此类进行扫描操作

  • 用法

    • 定义一个bean类,此类要添加注解,默认的bean的id值就是类名的头一个字母小写

    • 通过@Value注解对此属性赋值

      package com.gec.bean;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class Car {    @Value("特斯拉")    private String brand;    @Value("100000.00")    private Double price;    public String getBrand() {        return brand;    }    public void setBrand(String brand) {        this.brand = brand;    }    public Double getPrice() {        return price;    }    public void setPrice(Double price) {        this.price = price;    }    @Override    public String toString() {        return "Car{" +                "brand='" + brand + '\'' +                ", price=" + price +                '}';    }}
      
    • 扫描Car的bean对象

      <?xml version="1.0" encoding="UTF-8"?>
      <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 https://www.springframework.org/schema/context/spring-context.xsd">
      
          <context:component-scan base-package="com.gec.bean" />
      
      </beans>
      
    • 配置扫描过滤条件

      • 设置context:componet-scan下的,此时指定的include-filter没有起到作用,只要把use-default-filter设置成false就可以

        • include-filter:扫描目标类的过滤条件

        • exclude-filter:将扫描到目标类排除之外

          [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V6MNDq9V-1631536006440)(assets/image-20210910142849360.png)]

六、如何实现注解自装配bean对象

1、简介

  • 使用@Autowire实现自装配bean对象

2、@Autowire如何使用

  • @Autowire

    • 作用:查询IOC容器,将匹配的bean类型自动注入到bean的属性里面
  • 用法

    • 定义一个UserDao类

      package com.gec.dao;
      
      import org.springframework.stereotype.Repository;
      
      @Repository
      public class UserDao {
      
      
          public void save()
          {
              System.out.println("user dao save");
          }
      }
      
      
    • 定义一个UserService类

      • @Autowried
        • 查找ioc容器匹配bean对象类型自动注入到属性
      package com.gec.service;
      
      
      import com.gec.dao.UserDao;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      
      @Service
      public class UserService {
      
          @Autowired
          private UserDao userDao;
      
      
          public void save()
          {
              System.out.println("user service save");
              userDao.save();
          }
      
      
      }
      
      
    • 配置beans.xml,实现扫描bean类

      <?xml version="1.0" encoding="UTF-8"?>
      <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 https://www.springframework.org/schema/context/spring-context.xsd">
      
          <context:component-scan base-package="com.gec" />
      
      
      
      </beans>
      
    • 测试类

      package com.gec.app;
      
      import com.gec.service.UserService;
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      
      public class MainTest3 {
      
          public static void main(String[] args) {
      
              ApplicationContext ctx=new ClassPathXmlApplicationContext("beans3.xml");
      
      
              UserService userService= (UserService) ctx.getBean("userService");
      
              userService.save();
      
      
      
          }
      }
      
      

3、@Qualifier注解用法

  • 当注入数据类型,在一个IOC容器存在多个bean对象是属于相同的数据类型,则可以通过@Qualifier注解区分,具体导入那个bean对象

    value属性:就是指明bean id值
    
  • 用法

    • 定义一个UserDao接口
    package com.gec.dao;
    
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface UserDao {
    
    
        public void save();
    
    }
    
    
    • 分别两个实现类,实现于此接口

      package com.gec.dao.impl;
      
      import com.gec.dao.UserDao;
      import org.springframework.stereotype.Repository;
      
      @Repository
      public class UserDaoAImpl implements UserDao {
      
          @Override
          public void save() {
              System.out.println("UserDaoAImpl save");
          }
      }
      
      
    package com.gec.dao.impl;
    
    import com.gec.dao.UserDao;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class UserDaoBImpl implements UserDao {
    
        @Override
        public void save() {
            System.out.println("UserDaoBImpl save");
        }
    }
    
    
package com.gec.service;


import com.gec.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    @Qualifier(value = "userDaoBImpl")
    private UserDao userDao;


    public void save()
    {
        System.out.println("user service save");
        userDao.save();
    }

}

七、java加注解方式配置bean对象

1、简介

  • 通过纯的java+注解方式实现bean对象的配置

2、如何配置bean对象

  • @Configuration

    • 此注解修饰类,此类就是作用于配置bean的对象,此类就是之前beans.xml文件
  • @Bean

    • 此注解修饰方法,此方法就是配置bean对象,此方法名就是bean的id值
  • 用法

    • 直接定义一个类即可,不需要添加任何注解
    package com.gec.bean;
    
    public class Car {
    
        private String brand;
        private Double price;
    
        public String getBrand() {
            return brand;
        }
    
        public void setBrand(String brand) {
            this.brand = brand;
        }
    
        public Double getPrice() {
            return price;
        }
    
        public void setPrice(Double price) {
            this.price = price;
        }
    
        @Override
        public String toString() {
            return "Car{" +
                    "brand='" + brand + '\'' +
                    ", price=" + price +
                    '}';
        }
    }
    
    
    • 定义一个配置类
    package com.gec.conf;
    
    import com.gec.bean.Car;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class BeanConf {
    
        /*
        * 创建一个bean对象
        * bean的id就是方法名
        * */
        @Bean
        public Car car()
        {
            Car c=new Car();
            c.setBrand("QQ跑车");
            c.setPrice(300000.00);
            return c;
        }
    
    
    
    }
    
    

3、注解+扫描方式实现bean的配置

  • 在类添加四大注解之一(@Repository、@Service、@Controller都属于@Component)

  • 在配置类添加@ComponentScan

    • 实现扫描
  • 用法

    package com.gec.bean;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class Person {
    }
    
    
    package com.gec.conf;
    
    import com.gec.bean.Car;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan(value = "com.gec.bean")
    public class BeanConf {
    
        /*
        * 创建一个bean对象
        * bean的id就是方法名
        * */
        @Bean
        public Car car()
        {
            Car c=new Car();
            c.setBrand("QQ跑车");
            c.setPrice(300000.00);
            return c;
        }
    
    
    
    }
    
    
    • 测试类
    package com.gec.app;
    
    import com.gec.bean.Car;
    import com.gec.bean.Person;
    import com.gec.conf.BeanConf;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class MainTest {
    
        public static void main(String[] args) {
    
            ApplicationContext ctx=new AnnotationConfigApplicationContext(BeanConf.class);
    
            Car car= (Car) ctx.getBean("car");
    
            System.out.println(car);
    
            Person p= (Person) ctx.getBean("person");
            System.out.println(p);
    
    
        }
    }
    
    

八、如何java配置类引入xml配置

1、简介

  • 在java conf类导入xml配置

    @ImportResource("classpath:beans.xml")
    

2、具体用法

  • 定义beans.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" xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!--定义Car的bean对象-->
        <bean id="car" class="com.gec.bean.Car"
            p:brand="宝马" p:price="500000.00"
        />
    
    </beans>
    
  • 编写java conf类

    package com.gec.conf;
    
    import com.gec.bean.Boss;
    import com.gec.bean.Car;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.ImportResource;
    
    @Configuration
    @ImportResource("classpath:beans.xml")
    public class BeanConf2 {
    
        @Autowired
        private Car car;
    
        @Bean
        public Boss boss()
        {
            Boss boss=new Boss();
            boss.setBossName("许老板");
            boss.setCar(car);
    
            return boss;
    
        }
    
    }
    
    
  • 操作类

    package com.gec.app;
    
    import com.gec.bean.Boss;
    import com.gec.conf.BeanConf2;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class MainTest2 {
    
        public static void main(String[] args) {
    
            ApplicationContext ctx=new AnnotationConfigApplicationContext(BeanConf2.class);
    
            Boss boss= (Boss) ctx.getBean("boss");
    
            System.out.println(boss.getBossName());
            System.out.println(boss.getCar());
    
    
        }
    }
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值