加载中...

spring对象声明与注入的几种方式

1.1基于xml的配置

spring配置文件

<?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="myStudent" class="com.springboot.entity.Student">
        <property name="name" value="蔡剑波"/>
        <property name="age" value="20"/>
        <property name="sex" value="女"/>
    </bean>
</beans>
public class Student {

    private String name;
    private String sex;
    private int age;

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

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

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

测试类:

public class TestXmlConfig {

    @Test
    public void test01(){
        String config = "beans.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        // myStudent 是xml配置文件中配置的bean id属性值。
        Student myStudent = (Student) ctx.getBean("myStudent");
        System.out.println("获取的对象为: "+ myStudent);

    }
}
1.2 JavaConfig

​ javaConfig : 使用java类代替xml配置文件,是spring 提供的一种基于纯java类的配置方式。在这个配置类中@Bean创建java对象,并把对象注入到容器中。

需要使用2个注解:

  1. @Configuration: 这个注解作用在类上面,表示当前作用的类被当作配置文件使用。
  2. @Bean: 作用于方法上,表示声明对象,把对象注入到容器中。

创建配置类 MyConfig

import com.springboot.entity.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class MyConfig {
    /**
    *	@Bean: 注解
    	属性: name 相当于 bean标签中的id	
    	注解没有标注name属性值的话,默认就是方法的名称 getStudent
    */
    
    @Bean
    public Student getStudent(){
        Student student = new Student();
        student.setAge(18);
        student.setName("王五");
        student.setSex("男");
        return student;
    }
}

测试类

import com.springboot.config.MyConfig;
import com.springboot.entity.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@Test
    public void test02(){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
		// @Bean 注解没有指出name属性值,默认是方法名称 getStudent
        Student myStudent = (Student) ctx.getBean("getStudent");
        System.out.println("获取的对象为: "+ myStudent);

    }
1.3@ImportResource(导入xml配置文件,*.xml)

编写实体类Cat:

public class Cat {

    private String name;
    private int age;
    private String id;

    public Cat() {
    }

    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 getId() {
        return id;
    }

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

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

编写配置文件applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myCat" class="com.springboot.entity.Cat">
        <property name="age" value="18"/>
        <property name="id" value="um020303"/>
        <property name="name" value="tom猫"/>
    </bean>
</beans>

配置类添加注解@ImportResource,导入配置文件applicationContext.xml

ps: classpath:applicationContext.xml 是类路径下的文件,编译后会在类路径下。

package com.springboot.config;


import com.springboot.entity.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

/**
 * @author caijianbo
 * @ClassName MyConfig
 * @Date 2023/2/22 21:28
 * @version: 1.0
 **/
@Configuration
@ImportResource(value = "classpath:applicationContext.xml")
public class MyConfig {

    @Bean
    public Student getStudent(){
        Student student = new Student();
        student.setAge(18);
        student.setName("王五");
        student.setSex("男");
        return student;
    }

}

编写测试类:

import com.springboot.entity.Cat;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestXmlConfig {

    @Test
    public void test03(){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
        Cat cat = (Cat) ctx.getBean("myCat");
        System.out.println("cat>>>> "+ cat);
    }
}
1.4@PropertySource 读取属性配置文件(*.properties)

读取属性配置文件,可以实现外部化配置,读取代码之外的配置文件。

步骤:

  1. 在resources目录下,创建properties文件,使用k=v格式提供数据。
  2. 在@PropertySource指定配置文件的路径。
  3. 使用@Value(value="${}")设置属性的值。引用的是properties文件中的值。

创建实体类Tiger

ackage com.springboot.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author caijianbo
 * @ClassName Tiger
 * @Date 2023/2/28 21:33
 * @version: 1.0
 **/
// @Component(value = "tiger") 创建对象,名称为“tiger”
@Component(value = "tiger")
public class Tiger {
    //@Value(value = "${tiger.name}") 注入properties配置文件中的数据
    @Value(value = "${tiger.name}")
    private String name;
    @Value(value = "${tiger.age}")
    private String age;

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

编写属性配置文件

在resources目录下编写属性配置文件。

tiger.name=东北老虎
tiger.age=3

编写MyConfig 配置类

package com.springboot.config;


import com.springboot.entity.Student;
import org.springframework.context.annotation.*;

/**
 * @author caijianbo
 * @ClassName MyConfig
 * @Date 2023/2/22 21:28
 * @version: 1.0
 **/
@Configuration
//@PropertySource(value = "classpath:app.properties")读取类路径下的属性配置文件
@PropertySource(value = "classpath:app.properties")
//配置组件扫描范围。扫描哪个包下面的类
@ComponentScan(basePackages = "com.springboot.entity")
@SuppressWarnings(value = "all")
public class MyConfig {

    @Bean
    public Student getStudent(){
        Student student = new Student();
        student.setAge(18);
        student.setName("王五");
        student.setSex("男");
        return student;
    }

}

测试类

import com.springboot.config.MyConfig;
import com.springboot.entity.Tiger;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author caijianbo
 * @ClassName TestXmlConfig
 * @Date 2023/2/22 20:32
 * @version: 1.0
 **/
public class TestXmlConfig {

    @Test
    public void test04(){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
        Tiger tiger = (Tiger) ctx.getBean("tiger");
        System.out.println(tiger);
    }

}

posted @ 2023-02-28 22:13  兔子的胡萝卜  阅读(72)  评论(0)    收藏  举报