Spring之对象创建(IOC)

方式一基于XML

首先我们要知道一些基本概念
在这里插入图片描述

普通赋值法

1.导入Spring的包
在这里插入图片描述
下载地址:https://wws.lanzoui.com/iu7ndp7x8wf

2.创建Bean.xml文件并且进行配置
具体的有一些细节地方 写在了注释里面 回看的时候记得看注释

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util.xsd ">

    <!--用这个util必须要在上面添加两个东西-->
    <!--第一个  xmlns:util="http://www.springframework.org/schema/util"-->
    <!--第二个 在 xsi:schemaLocation里复制第一行 然后把beans改成util就ok-->
    <util:list id="list">
        <value>"xzh1"</value>
        <value>"xzh2"</value>
        <value>"xzh3"</value>
        <value>"xzh4"</value>
    </util:list>


    <!--scope可以设置多实例还是单实例
                prototype为多实例 即每次getBean得到的地址不一样
                singleton为单实例 即每次getBean得到一样的地址-->
    <bean id="Stu" class="com.xzh.Stu.Stu" scope="prototype">
        <!--property标签是调用set方法给他赋初值
         这个bean标签都是用这个方法-->

        <!--普通属性注入(赋初值)方法-->
        <property name="name">
            <value >"张三"</value>
        </property>


        <!--数组注入 必须要有array标签  还有就是方法中要有set方法-->
        <property name="courses">
            <array>
                <value>"xzh1"</value>
                <value>"xzh2"</value>
                <value>"xzh3"</value>
                <value>"xzh4"</value>
            </array>
        </property>


        <!--list注入 必须要有list标签  还有就是方法中要有set方法-->
        <!--这里的ref是引入了  util:list这个标签的值 list为他的id
        就不用再像之前那样输入值了 提高了重复调用行-->
        <property name="list" ref="list"></property>
        <!--map注入 必须要有map标签  还有就是方法中要有set方法-->
        <property name="map">
            <map>
                <entry key="xzh1" value="XZH1"></entry>
                <entry key="xzh2" value="XZH2"></entry>
                <entry key="xzh3" value="XZH3"></entry>
                <entry key="xzh4" value="XZH4"></entry>
            </map>
        </property>


        <!--set注入 必须要有set标签  还有就是方法中要有set方法-->
        <property name="set">
            <set>
                <value>"xzh1"</value>
                <value>"xzh2"</value>
                <value>"xzh3"</value>
                <value>"xzh4"</value>
            </set>
        </property>


        <!--list 对象 注入 必须要有list标签  还有就是方法中要有set方法-->
        <!--首先要创建一个这个对应对象(Person)的bean标签 然后通过ref引用-->
        <property name="listPerson">
            <list>
                <ref bean="Person1"/>
                <ref bean="Person2"/>
            </list>
        </property>
    </bean>


    <!--person类的bean-->
    <bean name="Person1" class="com.xzh.Stu.Person" >
        <!--constructor-arg是调用构造器方法-->
        <!--这个bean都是用的这个方法-->
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="name" value="Person18"></constructor-arg>
    </bean>
    <bean name="Person2" class="com.xzh.Stu.Person">
        <constructor-arg name="age" value="19"></constructor-arg>
        <constructor-arg name="name" value="Person19"></constructor-arg>
    </bean>
</beans>

Test1.java测试文件 (实例化对象的文件)

package com.xzh.Stu;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/5/17 19:05
 */
public class TestStru {
    @Test
    public void test1(){
        //从配置文件中得到信息 后面的那个"beanStu.xml" 是配置文件的文件名
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("beanStu.xml");
        //用得到的信息 创建对象  "Stu"是bean标签中对应的name  Stu.Class是要创建的对象类型
        Stu stu1 = applicationContext.getBean("Stu", Stu.class);
        System.out.println(stu1);
    }
}

对应的Stu类:

package com.xzh.Stu;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/5/17 18:58
 */
public class Stu {
    private String name;
    private String[] courses;
    private List<String> list;
    private Map<String, String> map;
    private Set<String> set;
    private List<Person> listPerson;

    public Stu() {
    }

    public Stu(String name, String[] courses, List< String > list, Map< String, String > map, Set< String > set, List< Person > listPerson) {
        this.name = name;
        this.courses = courses;
        this.list = list;
        this.map = map;
        this.set = set;
        this.listPerson = listPerson;
    }

    public String getName() {
        return name;
    }

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

    public String[] getCourses() {
        return courses;
    }

    public void setCourses(String[] courses) {
        this.courses = courses;
    }

    public List< String > getList() {
        return list;
    }

    public void setList(List< String > list) {
        this.list = list;
    }

    public Map< String, String > getMap() {
        return map;
    }

    public void setMap(Map< String, String > map) {
        this.map = map;
    }

    public Set< String > getSet() {
        return set;
    }

    public void setSet(Set< String > set) {
        this.set = set;
    }

    public List< Person > getListPerson() {
        return listPerson;
    }

    public void setListPerson(List< Person > listPerson) {
        this.listPerson = listPerson;
    }


    @Override
    public String toString() {
        return "Stu{" +
                "name='" + name + '\'' +
                ", courses=" + Arrays.toString(courses) +
                ", list=" + list +
                ", map=" + map +
                ", set=" + set +
                ", listPerson=" + listPerson +
                '}';
    }
}


对应用到的person类

package com.xzh.Stu;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/5/17 19:24
 */
public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }



    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

引入外部文件值赋值法

引入外部文件值的方法:

<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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标签-->
    <!--使用context:component-scan 标签
    ase-package是选择需要开启扫的包的路径 里面的文件代表 它和它的子包都会被扫描到-->
<context:component-scan base-package="com.xzh"/>


    <!--示例 1
 use-default-filters="false" 表示现在不使用默认 filter,自己配置 filter
 context:include-filter ,设置扫描哪些内容(这里是设置的Controller这个注解开启扫描)
-->
    <context:component-scan base-package="com.xzh" use-default-filters="false">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--示例 2
     下面配置扫描包所有内容
     context:exclude-filter: 设置哪些内容不进行扫描(这里是设置的Controller这个注解不扫描)
    -->
    <context:component-scan base-package="com.xzh">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

对应的jdbc.properties文件

jdbc.url=jdbc:mysql://localhost:3306/book
jdbc.username=root
jdbc.password=000000

怎么在xml中加载properties?

首先导入context空间

xmlns:context=http://www.springframework.org/schema/context

然后用这种方式来加载

<!--加载外部文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>

如何使用:里面的东西 ${jdbc.username} jdbc.username对应的是key

详细代码:

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

    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
    </bean>
</beans>

方式二 基于注解的方法

首先知道每个注解有什么用:
在这里插入图片描述
在这里插入图片描述

具体的细节我写在了注释里面

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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标签-->
    <!--使用context:component-scan 标签
    ase-package是选择需要开启扫的包的路径 里面的文件代表 它和它的子包都会被扫描到-->
<context:component-scan base-package="com.xzh"/>



    <!--示例 1
 use-default-filters="false" 表示现在不使用默认 filter,自己配置 filter
 context:include-filter ,设置扫描哪些内容(这里是设置的Controller这个注解开启扫描)
-->
    <context:component-scan base-package="com.xxx" use-default-filters="false">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--示例 2
     下面配置扫描包所有内容
     context:exclude-filter: 设置哪些内容不进行扫描(这里是设置的Controller这个注解不扫描)
    -->
    <context:component-scan base-package="com.xxx">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

UserService类:

package com.xzh.Spring5.Annotation;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/5/18 15:19
 */

import com.xzh.Spring5.dao.UserDao;
import com.xzh.Spring5.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.Service;
/**
 * //**********************创建对象的注解***************
 * @Component 控制器(注入服务), 用于标注控制层组件(如struts中的action)
 * @Service 服务(注入dao), 用于标注业务层组件
 * @Repository dao(实现dao访问), 用于标注数据访问组件,即DAO组件
 * @Controller 把普通pojo实例化到spring容器中
 * 上面这4个都可以实现对象创建  但是建议在哪一层就用哪一个
 */

//这个value值就等于我们用bean标签的id标签
//可以省略value 那么默认值就是 类名第一个字母小写
@Service(value = "userService")
public class UserService {
    String name;
    @Value(value = "18")
    Integer age;
    /**
     * //**********************注入值的注解***************
     * 基于注解方式的注入方法
     * @AutoWireds  根据属性类型进行自动注入 可以单独使用
     * @Qualifiers  根据属性名称进行注入  必须和上面一起使用
     * @Resource    根据类型或属性注入 后期新版java好像已经没有了
     * @Value       普通注入
     */

    @Autowired//使用注解注入  根据属性类别自动注入
    @Qualifier(value = "userDaoImpl") //value必须要有  值就是在对象创建时注解里的value  即bean标签中的id
    UserDaoImpl userDaoImpl;

    @Autowired
    UserDao userDao;

    public void show() {
        System.out.println("UserService   我是用户************");
        userDaoImpl.show();
        userDao.show();
    }

    @Override
    public String toString() {
        return "UserService{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", userDaoImpl=" + userDaoImpl +
                ", userDao=" + userDao +
                '}';
    }
}


UserDao接口类

package com.xzh.Spring5.dao;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/5/18 15:48
 */
public interface UserDao {
    void  show();
}


UserDaoImpl接口实现类

package com.xzh.Spring5.dao;

import org.springframework.stereotype.Repository;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/5/18 15:48
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void show() {
        System.out.println("UserDaoImpl    *************");
    }
}

测试类

import com.xzh.Spring5.Annotation.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/5/18 15:24
 */
public class TestSpring {
    @Test
    public void test1() {
        //实例化方法还是和之前的一样
        ClassPathXmlApplicationContext classPathXmlApplicationContext =
                new ClassPathXmlApplicationContext("Annotation.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);

        System.out.println(userService);
        userService.show();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值