Spring学习(三)Spring配置bean对象

Spring学习(三)Spring配置bean对象

一、spring对象的获取及属性赋值方式

1、通过bean的id获取IOC容器中的对象

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        //根据bean标签的id来获取对象
        User user = (User) context.getBean("user");
        System.out.println(user);
    }
}

2、通过bean的类型获取对象

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        //根据bean类型来获取对象
        //注意 但通过类型去获取的时候,如果存在两个相同类型的对象,会因为程序无法判断使用哪个而报错
        User user = context.getBean(User.class);
        System.out.println(user);
    }
}

多个同类型bean报错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">
    <!--注册一个对象,spring会自动创建这个对象放入ioc容器中-->
    <!--
    一个bean标签就表示一个对象
    id:这个对象的唯一标识
    class:注册对象的完全限定名
    -->
    <bean id="user" class="com.zhow.bean.User">
        <!--使用property标签给对象的属性赋值
        name:表示属性的名称
        value:表示属性的值
        -->
        <property name="id" value="1"/>
        <property name="name" value="zhow"/>
        <property name="age" value="18"/>
        <property name="gender" value=""/>
    </bean>

    <bean id="user2" class="com.zhow.bean.User">
        <property name="id" value="2"/>
        <property name="name" value="jy"/>
        <property name="age" value="18"/>
        <property name="gender" value=""/>
    </bean>
</beans>

结果:

No qualifying bean of type 'com.zhow.bean.User' available: expected single matching bean but found 2: user,user2

没有可用的“com.zhow.bean.User”类型的合格 bean:预期单个匹配 bean,但找到 2个:user,user2

解决方法:可以使用 getBean(String s, Class aClass) 方式获取

3、通过构造器给bean对象赋值

user类加入构造方法

public User() {
}

public User(Integer id, String name, Integer age, String gender) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.gender = gender;
}

ioc.xml 配置文件

<!--给user类添加构造方法
 使用构造方法复制的时候,参数的name属性是由构造方法的参数名称决定的-->
<bean id="user2" class="com.zhow.bean.User">
    <constructor-arg name="id" value="2"/>
    <constructor-arg name="name" value="jy"/>
    <constructor-arg name="age" value="18"/>
    <constructor-arg name="gender" value=""/>
</bean>

<!--在使用构造器赋值的时候可以省略name属性,但是此时就要求必须严格按照构造器参数的顺序来填写了-->
<bean id="user3" class="com.zhow.bean.User">
        <constructor-arg value="3"></constructor-arg>
        <constructor-arg value="zhangsan"></constructor-arg>
        <constructor-arg value="20"></constructor-arg>
        <constructor-arg value=""></constructor-arg>
</bean>

<!--如果想不按照顺序来添加参数值,那么可以搭配index属性来使用-->
<bean id="user4" class="com.zhow.bean.User">
        <constructor-arg value="lisi" index="1"></constructor-arg>
        <constructor-arg value="4" index="0"></constructor-arg>
        <constructor-arg value="" index="3"></constructor-arg>
        <constructor-arg value="20" index="2"></constructor-arg>
</bean>

<!--当有多个参数个数相同,不同类型的构造器的时候,会使用排在上面的构造方法-->
<!--
public User(Integer id, String name, String gender) {
        this.id = id;
        this.name = name;
        this.gender = gender;
    }

    public User(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
-->
<bean id="user5" class="com.zhow.bean.User">
        <constructor-arg value="5"></constructor-arg>
        <constructor-arg value="wangwu"></constructor-arg>
        <constructor-arg value="22"></constructor-arg>
</bean>

    <!--当有多个参数个数相同,不同类型的构造器的时候,可以通过type来强制类型-->
<bean id="user6" class="com.zhow.bean.User">
        <constructor-arg value="6"></constructor-arg>
        <constructor-arg value="wangwu"></constructor-arg>
        <constructor-arg value="22" type="java.lang.Integer"></constructor-arg>
</bean>

4、通过命名空间为bean赋值,简化配置文件中属性声明的写法

xml 加入xmlns:p=“http://www.springframework.org/schema/p”

<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">
     <!--配置-->
    <bean id="user7" class="com.zhow.bean.User" p:id="7" p:age="18" p:name="maliu" p:gender=""/>
    </beans>

5、为复杂类型进行赋值操作

在之前的测试代码中,我们都是给最基本的属性进行赋值操作,在正常的企业级开发中还会遇到给各种复杂类型赋值,如集合、数组、其他对象等。

Person.java

public class Person {
    private int id;
    private String name="dahuang";
    private int age;
    private String gender;
    private Address address;
    private String[] hobbies;
    private List<Book> books;
    private Set<Integer> sets;
    private Map<String,Object> maps;
    private Properties properties;

    public Person(int id, String name, int age, String gender) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        System.out.println("有参构造器");
    }

    public Person(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
        System.out.println("Age");
    }

    public Person(int id, String name, String gender) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        System.out.println("gender");
    }

    public Person() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public List<Book> getBooks() {
        return books;
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public String[] getHobbies() {
        return hobbies;
    }

    public void setHobbies(String[] hobbies) {
        this.hobbies = hobbies;
    }

    public Set<Integer> getSets() {
        return sets;
    }

    public void setSets(Set<Integer> sets) {
        this.sets = sets;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", address=" + address +
                ", hobbies=" + Arrays.toString(hobbies) +
                ", books=" + books +
                ", sets=" + sets +
                ", maps=" + maps +
                ", properties=" + properties +
                '}';
    }
}

Adress.java

public class Address {
    private String province;
    private String city;
    private String town;

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getTown() {
        return town;
    }

    public void setTown(String town) {
        this.town = town;
    }

    @Override
    public String toString() {
        return "Address{" +
                "province='" + province + '\'' +
                ", city='" + city + '\'' +
                ", town='" + town + '\'' +
                '}';
    }
}

Book.java

public class Book {
    private String name;
    private String author;
    private double price;

    public Book() {
    }

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

ioc.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" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

    <!--给复杂类型的赋值都在property标签内进行-->
    <bean id="person" class="com.zhow.bean.Person">
        <property name="name">
            <!--赋空值-->
            <null></null>
        </property>
        <!--通过ref引用其他对象,引用外部bean-->
        <property name="address" ref="address"></property>
        <!--引用内部bean-->
        <!-- <property name="address">
             <bean class="com.zhow.bean.Address">
                 <property name="province" value="北京"></property>
                 <property name="city" value="北京"></property>
                 <property name="town" value="西城区"></property>
             </bean>
         </property>-->
        <!--为list赋值-->
        <property name="books">
            <list>
                <!--内部bean-->
                <bean id="book1" class="com.zhow.bean.Book">
                    <property name="name" value="多线程"></property>
                    <property name="author" value="大佬"></property>
                    <property name="price" value="1000"></property>
                </bean>
                <!--外部bean-->
                <ref bean="book2"></ref>
            </list>
        </property>
        <!--给map赋值-->
        <property name="maps" ref="myMap"></property>
        <!--给property赋值-->
        <property name="properties">
            <props>
                <prop key="aaa">aaa</prop>
                <prop key="bbb">222</prop>
            </props>
        </property>
        <!--给数组赋值-->
        <property name="hobbies">
            <array>
                <value>book</value>
                <value>movie</value>
                <value>game</value>
            </array>
        </property>
        <!--给set赋值-->
        <property name="sets">
            <set>
                <value>111</value>
                <value>222</value>
                <value>222</value>
            </set>
        </property>
    </bean>
    <bean id="address" class="com.zhow.bean.Address">
        <property name="province" value="河北"></property>
        <property name="city" value="邯郸"></property>
        <property name="town" value="武安"></property>
    </bean>
    <bean id="book2" class="com.zhow.bean.Book">
        <property name="name" value="JVM"></property>
        <property name="author" value="大佬"></property>
        <property name="price" value="1200"></property>
    </bean>
    <!--级联属性-->
    <bean id="person2" class="com.zhow.bean.Person">
        <property name="address" ref="address"></property>
        <property name="address.province" value="北京"></property>
    </bean>
    <!--util名称空间创建集合类型的bean-->
    <util:map id="myMap">
        <entry key="key1" value="value1"></entry>
        <entry key="key2" value-ref="book2"></entry>
        <entry key="key03">
            <bean class="com.zhow.bean.Book">
                <property name="name" value="西游记" ></property>
                <property name="author" value="吴承恩" ></property>
                <property name="price" value="100" ></property>
            </bean>
        </entry>
    </util:map>

</beans>

二、spring创建第三方bean对象

在Spring中,很多对象都是单实例的,在日常的开发中,我们经常需要使用某些外部的单实例对象,例如数据库连接池,下面我们来讲解下如何在spring中创建第三方bean实例。

​ 1、导入数据库连接池的pom文件

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

​ 2、编写配置文件

ioc.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">

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    </bean>
</beans>

​ 3、编写测试文件

MyTest.java

import com.alibaba.druid.pool.DruidDataSource;
import com.zhow.bean.Person;
import com.zhow.bean.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        DruidDataSource dataSource = context.getBean("dataSource", DruidDataSource.class);
        System.out.println(dataSource);

    }
}

三、spring引用外部配置文件

在resource中添加dbconfig.properties

username=root
password=root
url=jdbc:mysql://localhost:3306/test
driverClassName=com.mysql.jdbc.Driver

编写配置文件

<?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" xmlns:util="http://www.springframework.org/schema/util"
       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/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  
    <!--加载外部配置文件 在加载外部依赖文件的时候需要context命名空间-->
    <context:property-placeholder location="classpath:dbconfig.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
        <property name="url" value="${url}"></property>
        <property name="driverClassName" value="${driverClassName}"></property>
    </bean>

</beans>

四、spring基于xml文件的自动装配

​ 当一个对象中需要引用另外一个对象的时候,在之前的配置中我们都是通过property标签来进行手动配置的,其实在spring中还提供了一个非常强大的功能就是自动装配,可以按照我们指定的规则进行配置,配置的方式有以下几种:

​ default/no:不自动装配

​ byName:按照名字进行装配,以属性名作为id去容器中查找组件,进行赋值,如果找不到则装配null

​ byType:按照类型进行装配,以属性的类型作为查找依据去容器中找到这个组件,如果有多个类型相同的bean对象,那么会报异常,如果找不到则装配null

​ constructor:按照构造器进行装配,先按照有参构造器参数的类型进行装配,没有就直接装配null;如果按照类型找到了多个,那么就使用参数名作为id继续匹配,找到就装配,找不到就装配null

ioc.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">

    <bean id="address" class="com.zhow.bean.Address">
        <property name="province" value="河北"></property>
        <property name="city" value="邯郸"></property>
        <property name="town" value="武安"></property>
    </bean>
    <bean id="person" class="com.zhow.bean.Person" autowire="byName"></bean>
    <bean id="person2" class="com.zhow.bean.Person" autowire="byType"></bean>
    <bean id="person3" class="com.zhow.bean.Person" autowire="constructor"></bean>
</beans>

五、SpEL的使用

​ SpEL:Spring Expression Language,spring的表达式语言,支持运行时查询操作对象

​ 使用#{…}作为语法规则,所有的大括号中的字符都认为是SpEL.

ioc.xml

    <bean id="person4" class="com.zhow.bean.Person">
        <!--支持任何运算符-->
        <property name="age" value="#{12*2}"></property>
        <!--可以引用其他bean的某个属性值-->
        <property name="name" value="#{address.province}"></property>
        <!--引用其他bean-->
        <property name="address" value="#{address}"></property>
        <!--调用静态方法-->
        <property name="hobbies" value="#{T(java.util.UUID).randomUUID().toString().substring(0,4)}"></property>
        <!--调用非静态方法-->
        <property name="gender" value="#{address.getCity()}"></property>
    </bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值