Spring 使用详解

简介: Spring 使用详解


引入spring及测试的依赖

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


测试类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表示标记为被扫描类

image.png

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

里面的@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);
}

}

目录
相关文章
|
Java Apache 数据库
spring boot 2.0之使用spring boot
spring boot依赖 每一个spring boot的发型版本都包含了所依赖的版本,如果升级spring boot版本,其依赖也会同步更新升级。maven的用户可以通过继承spring-boot-starter-parent。
5614 0
|
6天前
|
Java 数据库 开发者
详细介绍SpringBoot启动流程及配置类解析原理
通过对 Spring Boot 启动流程及配置类解析原理的深入分析,我们可以看到 Spring Boot 在启动时的灵活性和可扩展性。理解这些机制不仅有助于开发者更好地使用 Spring Boot 进行应用开发,还能够在面对问题时,迅速定位和解决问题。希望本文能为您在 Spring Boot 开发过程中提供有效的指导和帮助。
43 12
|
9天前
|
Java 应用服务中间件 Maven
SpringBoot项目打包成war包
通过上述步骤,我们成功地将一个Spring Boot应用打包成WAR文件,并部署到外部的Tomcat服务器中。这种方式适用于需要与传统Servlet容器集成的场景。
29 8
|
1月前
|
XML Java 应用服务中间件
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
294 17
Spring Boot 两种部署到服务器的方式
|
1月前
|
Dart 前端开发 JavaScript
springboot自动配置原理
Spring Boot 自动配置原理:通过 `@EnableAutoConfiguration` 开启自动配置,扫描 `META-INF/spring.factories` 下的配置类,省去手动编写配置文件。使用 `@ConditionalXXX` 注解判断配置类是否生效,导入对应的 starter 后自动配置生效。通过 `@EnableConfigurationProperties` 加载配置属性,默认值与配置文件中的值结合使用。总结来说,Spring Boot 通过这些机制简化了开发配置流程,提升了开发效率。
76 17
springboot自动配置原理
|
4月前
|
人工智能 自然语言处理 前端开发
SpringBoot + 通义千问 + 自定义React组件:支持EventStream数据解析的技术实践
【10月更文挑战第7天】在现代Web开发中,集成多种技术栈以实现复杂的功能需求已成为常态。本文将详细介绍如何使用SpringBoot作为后端框架,结合阿里巴巴的通义千问(一个强大的自然语言处理服务),并通过自定义React组件来支持服务器发送事件(SSE, Server-Sent Events)的EventStream数据解析。这一组合不仅能够实现高效的实时通信,还能利用AI技术提升用户体验。
393 2
|
1月前
|
XML JavaScript Java
SpringBoot集成Shiro权限+Jwt认证
本文主要描述如何快速基于SpringBoot 2.5.X版本集成Shiro+JWT框架,让大家快速实现无状态登陆和接口权限认证主体框架,具体业务细节未实现,大家按照实际项目补充。
98 11
|
1月前
|
缓存 安全 Java
Spring Boot 3 集成 Spring Security + JWT
本文详细介绍了如何使用Spring Boot 3和Spring Security集成JWT,实现前后端分离的安全认证概述了从入门到引入数据库,再到使用JWT的完整流程。列举了项目中用到的关键依赖,如MyBatis-Plus、Hutool等。简要提及了系统配置表、部门表、字典表等表结构。使用Hutool-jwt工具类进行JWT校验。配置忽略路径、禁用CSRF、添加JWT校验过滤器等。实现登录接口,返回token等信息。
477 12
|
2月前
|
Java 数据库连接 Maven
最新版 | 深入剖析SpringBoot3源码——分析自动装配原理(面试常考)
自动装配是现在面试中常考的一道面试题。本文基于最新的 SpringBoot 3.3.3 版本的源码来分析自动装配的原理,并在文未说明了SpringBoot2和SpringBoot3的自动装配源码中区别,以及面试回答的拿分核心话术。
最新版 | 深入剖析SpringBoot3源码——分析自动装配原理(面试常考)
|
1月前
|
Java 测试技术 应用服务中间件
Spring Boot 如何测试打包部署
本文介绍了 Spring Boot 项目的开发、调试、打包及投产上线的全流程。主要内容包括: 1. **单元测试**:通过添加 `spring-boot-starter-test` 包,使用 `@RunWith(SpringRunner.class)` 和 `@SpringBootTest` 注解进行测试类开发。 2. **集成测试**:支持热部署,通过添加 `spring-boot-devtools` 实现代码修改后自动重启。 3. **投产上线**:提供两种部署方案,一是打包成 jar 包直接运行,二是打包成 war 包部署到 Tomcat 服务器。
50 10