Spring IOC

1、Spring 框架

1.1、环境搭建

1.1.1、创建 Maven 的 jar 项目

1.1.2、引入依赖

<!-- 添加 Spring 框架的核心依赖 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.4.RELEASE</version>
</dependency>

1.1.3、创建 bean 对象

public class UserService {
    public void test01(){
        System.out.println("UserService test01.....");
    }
}
public class AccountService {
    public void test01(){
        System.out.println("AccountService test01.....");
    }
}

1.1.4、添加 Spring01 配置文件

<?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">

    <!--
      id:bean 对象的名称,默认是对象名称的首字母小写
      class:bean 对象的类路径
      scope:作用域
        singleton:单例的 默认值
        prototype:原型的、非单例
      -->
    <bean id="userService" class="com.yjxxt.service.UserService" scope="prototype"></bean>
    <bean id="accountService" class="com.yjxxt.service.AccountService"></bean>

</beans>

1.1.5、测试

public class TestSpring {

    @Test
    public void test01(){
        
        // 获取配置文件,可读多个
        ApplicationContext app = new ClassPathXmlApplicationContext("spring01.xml");
        // 获取 bean
        UserService us = app.getBean("userService", UserService.class);
        AccountService as = app.getBean("accountService", AccountService.class);
        // 调用方法
        us.test01();
        as.test01();

    }
}

2、Spring 框架实例化对象

2.1、默认构造器实例化

public class User {

    private Integer id;
    private String name;

    public User() {}

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
<!--  通过无参构造器实例化对象  -->
<bean id="user1" class="com.yjxxt.bean.User">
    <!--  相当于 set()  -->
    <property name="id" value="1001"></property>
    <property name="name" value="zhangsan"></property>
</bean>

2.2、有参构造器实例化

public class User {

    private Integer id;
    private String name;

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

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
<!--  通过有参构造器实例化对象  -->
<bean id="user2" class="com.yjxxt.bean.User">
    <constructor-arg name="id" value="1002"></constructor-arg>
    <constructor-arg name="name" value="李四"></constructor-arg>
</bean>

2.3、静态工厂实例化

public class CarFactory1 {
    public static Car getCar(){
        return new Car("10454621", "劳斯莱斯幻影", 2000000);
    }
}
public class Car {

    private String number;
    private String name;
    private Integer price;

    public Car(String number, String name, Integer price) {
        this.number = number;
        this.name = name;
        this.price = price;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

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

    public Integer getPrice() {
        return price;
    }

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

    @Override
    public String toString() {
        return "Car{" +
                "number='" + number + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
<!--  通过静态工厂实例化对象  -->
<bean id="car1" class="com.yjxxt.factory.CarFactory1" factory-method="getCar"></bean>

2.4、非静态工厂实例化

public class CarFactory2 {
    public Car getCar(){
        return new Car("10454621", "劳斯莱斯幻影", 2000000);
    }
}
<!--  通过实例化工厂实例化对象  -->
<bean id="factory" class="com.yjxxt.factory.CarFactory2"></bean>
<bean id="car2" factory-bean="factory" factory-method="getCar"></bean>

3、Spring IOC 注入

3.1、xml 

public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private Double score;
    private Date birthday;
    private List<String> subject;
    private Set<String> hobby;
    private Map<String, Object> bankCard;
    private Properties properties;
    private String [] eat;
    private Car myCar;

    public Student() {}

    public Integer getId() {
        return id;
    }

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

    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;
    }

    public Double getScore() {
        return score;
    }

    public void setScore(Double score) {
        this.score = score;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public List<String> getSubject() {
        return subject;
    }

    public void setSubject(List<String> subject) {
        this.subject = subject;
    }

    public Set<String> getHobby() {
        return hobby;
    }

    public void setHobby(Set<String> hobby) {
        this.hobby = hobby;
    }

    public Map<String, Object> getBankCard() {
        return bankCard;
    }

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

    public Properties getProperties() {
        return properties;
    }

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

    public String[] getEat() {
        return eat;
    }

    public void setEat(String[] eat) {
        this.eat = eat;
    }

    public Car getMyCar() {
        return myCar;
    }

    public void setMyCar(Car myCar) {
        this.myCar = myCar;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                ", birthday=" + birthday +
                ", subject=" + subject +
                ", hobby=" + hobby +
                ", bankCard=" + bankCard +
                ", properties=" + properties +
                ", eat=" + Arrays.toString(eat) +
                ", myCar=" + myCar +
                '}';
    }
}
<?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="date" class="java.util.Date">
        <property name="year" value="2021"></property>
        <property name="month" value="9"></property>
        <property name="date" value="06"></property>
    </bean>

    <!--  静态工厂实例化  -->
    <bean id="car" class="com.yjxxt.factory.CarFactory1" factory-method="getCar">
        <property name="name" value="法拉利"></property>
    </bean>

    <bean id="stu" class="com.yjxxt.bean.Student">
        <property name="id" value="20210906"></property>
        <property name="name" value="张三"></property>
        <property name="age" value="20"></property>
        <property name="score" value="59.9"></property>
        
        <!--  参考日期对象  -->
        <property name="birthday" ref="date"></property>
        
        <!--  注入 list  -->
        <property name="subject">
            <list>
                <value>语文</value>
                <value>数学</value>
                <value>英语</value>
            </list>
        </property>
        
        <!--  注入 set  -->
        <property name="hobby">
            <set>
                <value>抽烟</value>
                <value>喝酒</value>
                <value>烫头</value>
            </set>
        </property>
        
        <!--  注入 map  -->
        <property name="bankCard">
            <map>
                <entry key="农业银行" value="10000"></entry>
                <entry key="储蓄银行" value="15000"></entry>
                <entry key="建设银行" value="20000"></entry>
            </map>
        </property>
        
        <!--  注入 properties  -->
        <property name="properties">
            <props>
                <prop key="省">安徽省</prop>
                <prop key="市">六安市</prop>
                <prop key="县">霍山县</prop>
            </props>
        </property>
        
        <!--  注入数组  -->
        <property name="eat">
            <array>
                <value>烧鸡</value>
                <value>红酒</value>
                <value>阿根达斯</value>
            </array>
        </property>
        
        <!--  注入 car  -->
        <property name="myCar" ref="car"></property>
    </bean>

</beans>

3.2、注解(自动装配)

3.2.1、@Autowired

        默认通过类型(Class 类型)查找 bean 对象,与属性字段的名称无关

public class UserDao {
    public void test01(){
        System.out.println("UserDao test01.....");
    }
}
public class ServiceDao {

    @Autowired
    public UserDao userDao;

    public void test01(){
        System.out.println("ServiceDao test01.....");
        userDao.test01();
    }
}
<?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:annotation-config/>

    <!--  实例化 UserDao -->
    <bean id="userDao" class="com.yjxxt.dao.UserDao"></bean>

    <!--  实例化 ServiceDao  -->
    <bean id="user" class="com.yjxxt.service.ServiceDao"></bean>

</beans>
public class TestUser {

    @Test
    public void test01(){
        ApplicationContext app = new ClassPathXmlApplicationContext("spring06.xml");
        ServiceDao user = app.getBean("user", ServiceDao.class);
        user.test01();
    }
}

        当类型相同时,需使用 @Qualifier 来指明对象的名称

public interface AccountDao {
    void save();
}
public class StudentDao implements AccountDao {

    @Override
    public void save() {
        System.out.println("StudentDao save.......");
    }
}
public class TeacherDao implements AccountDao {

    @Override
    public void save() {
        System.out.println("TeacherDao save.......");
    }
}
<?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:annotation-config/>

    <bean id="sd" class="com.yjxxt.dao.StudentDao"></bean>
    <bean id="td" class="com.yjxxt.dao.TeacherDao"></bean>
    <bean id="as" class="com.yjxxt.service.AccountService2"></bean>

</beans>
public class AccountService2 {

    @Autowired
    @Qualifier(value = "td")
    private AccountDao accountDao;

    public void test01(){
        System.out.println("AccountService2 test01....");
        accountDao.save();
    }
}
public class Test01 {

    @Test
    public void test01(){
        ApplicationContext app = new ClassPathXmlApplicationContext("spring07.xml");
        AccountService2 as = app.getBean("as", AccountService2.class);
        as.test01();
    }
}

3.2.2、@Resource

        通过名称查找对应的 bean 对象(属性字段的名称与 bean 标签的 id 属性值相等)

  引入依赖:

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>
public class ServiceDao {

    @Resource(name = "userDao")
    public UserDao userDao;

    public void test01(){
        System.out.println("ServiceDao test01.....");
        userDao.test01();
    }
}

        当 @Resource 不指定名称,默认按类型查找,相当于 @Autowired

4、自动扫描

4.1、设置自动扫描的范围

<?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.yjxxt"/>

</beans>

4.2、特定注解的使用

  • Dao 层:@Repository

  • Service 层:@Service

  • Controller 层:@Controller

  • 任意类:@Component

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值