Spring 使用详解

本文介绍了如何在Spring框架中引入依赖,并通过XML配置和注解方式进行Bean的定义与初始化。内容包括配置文件`applicationContext.xml`的编写,测试类的创建,以及使用注解`@Service`、`@Configuration`等进行简化配置。示例展示了Entity和Student类的定义,以及在测试中如何注入和使用这些Bean。
摘要由CSDN通过智能技术生成

引入spring及测试的依赖

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.16</version>
        </dependency>
        <!-- org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.16</version>
            <scope>test</scope>
        </dependency>

        <!-- org.junit.jupiter/junit-jupiter-api -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.2</version>
            <scope>test</scope>
        </dependency>

        <!-- org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>

在cn.chenxiejia.entity包下建一个Entity和Student类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Entity {
    private Set<Student> set;
    private Map<Integer, Student> map;
    private List<Student> list;
    private String[] s;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int sid;
    private String name;
    public void init() {
        System.out.println("初始化");
    }

    public void close() {
        System.out.println("执行了销毁");
    }
}

然后建一个spring的配置文件,spring的所有配置都在这里进行,当然,也可以使用注解的方式配置随后进行注解方式演示

配置文件applicationContext.xml

这里演示的各种类型属性的配置 配置思路是先进性扫包加载文件 再进行bean的配置 加载文件只加载一次即可

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context
https://www.springframework.org/schema/context/spring-context.xsd">
    <!--    扫描包-->
    <context:component-scan base-package="cn.chenxiejia.entity"/>
    <!--    加载properties文件-->
    <context:property-placeholder location="db.properties"/>

    <!--创建实例 init-method 初始化执行 destroy-method 销毁时执行-->
    <bean id="zhang" class="cn.chenxiejia.entity.Student" init-method="init" destroy-method="close">
        <constructor-arg index="0" value="1"/>
        <constructor-arg index="1" value="张同学"/>
    </bean>
    <bean id="li" class="cn.chenxiejia.entity.Student">
        <constructor-arg name="name" value="李同学"/>
        <constructor-arg name="sid" value="2"/>

    </bean>
    <bean id="wang" class="cn.chenxiejia.entity.Student">
        <constructor-arg value="3"/>
        <constructor-arg value="王同学"/>
    </bean>
    <!-- id name 不能相同 唯一识别-->
    <bean id="entity" class="cn.chenxiejia.entity.Entity">
        <property name="set">
            <set>
                <!--ref 为链接对象-->
                <ref bean="zhang"/>
                <ref bean="li"/>
                <ref bean="wang"/>
            </set>
        </property>
        <property name="list">
            <list>
                <ref bean="wang"/>
                <ref bean="zhang"/>
            </list>
        </property>
        <property name="map">
            <map>
                <entry key="1" value-ref="li"/>
                <entry key="2" value-ref="wang"/>
            </map>
        </property>
        <property name="s">
            <array value-type="java.lang.String">
                <value>ss</value>
                <value>dd</value>
                <value>ff</value>
            </array>
        </property>
    </bean>
    <bean id="entity1" name="entity2" class="cn.chenxiejia.entity.Entity">
        <property name="set">
            <set>
                <ref bean="zhang"/>
                <ref bean="li"/>
                <ref bean="wang"/>
            </set>
        </property>
        <property name="list">
            <list>
                <ref bean="wang"/>
                <ref bean="zhang"/>
            </list>
        </property>
        <property name="map">
            <map>
                <entry key="1" value-ref="li"/>
                <entry key="2" value-ref="wang"/>
            </map>
        </property>
        <property name="s">
            <array value-type="java.lang.String">
                <value>11</value>
                <value>sq</value>
                <value>ee</value>
            </array>
        </property>
    </bean>
</beans>

测试类1演示

//加载xml配置
@SpringJUnitConfig(locations = {"classpath:applicationContext.xml"})
public class Springdemo {
    //@Autowired为自动装配 写清楚类型及实例名,实例名必须唯一或者该类型只有一个实例
    @Autowired
    Student li;
    @Autowired
    ApplicationContext ac;
    @Autowired
    Entity entity1;
    @Autowired
    Entity entity;
    @Autowired
    Student zhang;

    @Test
    public void demo() {
        //getDeanDefinitionNames为bean实例化的名称列表
        for (String b : ac.getBeanDefinitionNames()) {
            System.out.println(b);
        }
        System.out.println(li);
    }
    //@Qualifier("") 将该对象属性赋值给另一个
    @Test
    public void demo1(@Qualifier("entity1") Entity e) {
        System.out.println(e.getList());
        System.out.println(e.getMap());
        System.out.println(e.getSet());
        for (String s : e.getS()) {
            System.out.println(s);
        }
    }

测试类2演示

@SpringJUnitConfig(locations = "classpath:applicationContext.xml")
//@PropertySource("db.properties")
public class SpringDemo1 {

    //#用于获取实例属性 $用于获取配置文件内容
    @Value("#{'zhang,li1,wang,zhao,li'.split(',')}")
    private List<String> list;
    @Value("${db.url}")
    private String url;
    @Value("#{li.name}")
    private String map;

    @Test
    public void demo1() {
        System.out.println(list);
        System.out.println(url);
        System.out.println(map);
    }
}

接下来使用注解的形式演示

在刚才的两个实体类上加个注解@Service表示标记为被扫描类

 然后创建一个配置类相当于之前的applicationContext.xml

里面的@Bean相当于<bean></bean>的配置

//标注为配置类
@Configuration
//扫描包
@ComponentScan("cn.chenxiejia.entity")
//加载配置文件
@PropertySource("classpath:db.properties")
public class AppConfig {
    @Bean(name = "s1", initMethod = "init", destroyMethod = "close")
    public Student Student(@Value("1") int id, @Value("张同学") String name) {
        return new Student(id, name);
    }

    @Bean(name = "s2", initMethod = "init", destroyMethod = "close")
    public Student Student2(@Value("2") int id, @Value("王同学") String name) {
        return new Student(id, name);
    }

    @Bean("e1")
    public Entity e1(@Value("#{{s1,s2}}") Set<Student> set, @Value("#{{3:s1,4:s2}}") Map<Integer, Student> map, @Value("#{{s1,s2}}") List<Student> list, @Value("#{'java,phton,js,c,html'.split(',')}") String[] s) {
        return new Entity(set, map, list, s);
    }

    @Bean("e2")
    public Entity e2(@Value("#{{s1,s2}}") Set<Student> set, @Value("#{{3:s1,4:s2}}") Map<Integer, Student> map, @Value("#{{s1,s2}}") List<Student> list, @Value("#{'aa,bb,cc,dd,ee'.split(',')}") String[] s) {
        return new Entity(set, map, list, s);
    }
}

然后简单测试一下

//加载配置类
@SpringJUnitConfig(AppConfig.class)
public class SpringDemo2 {
    @Autowired
    Student s2;
    @Autowired
    Entity e1;

    @Test
    public void demo1() {
        System.out.println(e1);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值