📕我是廖志伟,一名Java开发工程师、《Java项目实战——深入理解大型互联网企业通用技术》(基础篇)、(进阶篇)、(架构篇)、《解密程序员的思维密码——沟通、演讲、思考的实践》作者、清华大学出版社签约作家、Java领域优质创作者、优快云博客专家、阿里云专家博主、51CTO专家博主、产品软文专业写手、技术文章评审老师、技术类问卷调查设计师、幕后大佬社区创始人、开源项目贡献者。
📘拥有多年一线研发和团队管理经验,研究过主流框架的底层源码(Spring、SpringBoot、SpringMVC、SpringCloud、Mybatis、Dubbo、Zookeeper),消息中间件底层架构原理(RabbitMQ、RocketMQ、Kafka)、Redis缓存、MySQL关系型数据库、 ElasticSearch全文搜索、MongoDB非关系型数据库、Apache ShardingSphere分库分表读写分离、设计模式、领域驱动DDD、Kubernetes容器编排等。
📙不定期分享高并发、高可用、高性能、微服务、分布式、海量数据、性能调优、云原生、项目管理、产品思维、技术选型、架构设计、求职面试、副业思维、个人成长等内容。
💡在这个美好的时刻,笔者不再啰嗦废话,现在毫不拖延地进入文章所要讨论的主题。接下来,我将为大家呈现正文内容。
一、IoC容器核心依赖注入实现
在Spring框架中,控制反转(IoC)容器是实现依赖注入(DI)的关键,它通过自动创建对象实例和装配依赖关系来降低组件之间的耦合度。以下是IoC容器中依赖注入的几种实现模式的详细技术实现细节:
构造器注入
构造器注入通过在对象构造函数中注入依赖项,确保了对象在创建时就具备了所需的依赖关系。在Spring中,可以通过构造函数的参数类型来推断依赖项,例如:
public class ServiceClass {
private RepositoryClass repository;
public ServiceClass(RepositoryClass repository) {
this.repository = repository;
}
}
在Spring配置中,可以通过<constructor-arg>
标签来指定构造器注入的依赖项:
<bean id="serviceClass" class="com.example.ServiceClass">
<constructor-arg ref="repositoryClass"/>
</bean>
Setter注入
Setter注入是在对象的构造之后,通过setter方法设置依赖项。这种方式在Spring中通过<property>
标签实现:
public class ServiceClass {
private RepositoryClass repository;
public void setRepository(RepositoryClass repository) {
this.repository = repository;
}
}
<bean id="serviceClass" class="com.example.ServiceClass">
<property name="repository" ref="repositoryClass"/>
</bean>
字段注入
字段注入直接在类中声明依赖项的字段,并在对象创建时自动注入。在Spring中,可以使用@Autowired
注解实现字段注入:
public class ServiceClass {
@Autowired
private RepositoryClass repository;
}
方法注入
方法注入通过在类中定义方法,并在方法内部注入依赖项。在Spring中,可以通过@Autowired
注解结合自定义方法实现:
public class ServiceClass {
private RepositoryClass repository;
@Autowired
public void init(RepositoryClass repository) {
this.repository = repository;
}
}
组件扫描机制
组件扫描是通过扫描指定包下的类,自动检测带有特定注解的类,并将其注册为Bean。在Spring中,可以使用@ComponentScan
注解来指定扫描的包:
@SpringBootApplication
@ComponentScan("com.example")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Bean作用域
Spring允许配置Bean的作用域,包括单例(Singleton)和原型(Prototype)。单例作用域表示每个Spring容器中只有一个Bean实例,而原型作用域表示每次请求都会创建一个新的Bean实例。在Spring配置中,可以通过scope
属性来指定Bean的作用域:
<bean id="serviceClass" class="com.example.ServiceClass" scope="prototype"/>
条件化配置(@Conditional)
@Conditional
注解允许在运行时根据条件动态地创建或配置Bean。在Spring中,可以通过自定义条件实现,例如:
@Component
@Conditional(OnProfileCondition.class)
public class ServiceClass {
// ...
}
其中,OnProfileCondition
是一个条件类,它基于Spring的配置文件中指定的profile来决定是否创建Bean。
二、AOP技术体系
面向切面编程(AOP)是Spring框架中用于处理横切关注点的技术。以下是AOP技术体系的关键组成部分的详细技术实现细节:
代理模式实现
AOP通过代理模式实现,包括JDK动态代理和CGLIB代理。JDK动态代理适用于实现了接口的类,而CGLIB代理适用于没有实现接口的类。在Spring中,可以使用ProxyFactory
或AOPProxy
来创建代理对象:
Class<?>[] interfaces = new Class<?>[] {TargetInterface.class};
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setInterfaces(interfaces);
proxyFactory.setTarget(targetObject);
TargetInterface proxy = (TargetInterface) proxyFactory.getProxy();
切点表达式语法
切点表达式用于定义哪些方法应该被通知。在Spring AOP中,可以使用正则表达式或表达式语言来定义切点。例如:
PointcutExpression pointcut = PointcutExpressionBuilder.createPointcutExpression("execution(* com.example..*.*(..))");
通知类型
通知是AOP的核心,包括前置通知(Before)、后置通知(After)、环绕通知(Around)、异常通知(AfterThrowing)和最终通知(AfterReturning)。在Spring AOP中,可以使用@Before
、@After
、@Around
、@AfterThrowing
和@AfterReturning
注解来定义通知:
@Aspect
public class LoggingAspect {
@Before("execution(* com.example..*.*(..))")
public void beforeAdvice(JoinPoint joinPoint) {
// ...
}
@After("execution(* com.example..*.*(..))")
public void afterAdvice(JoinPoint joinPoint) {
// ...
}
@Around("execution(* com.example..*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
// ...
return joinPoint.proceed();
// ...
}
@AfterThrowing(pointcut = "execution(* com.example..*.*(..))", throwing = "ex")
public void afterThrowingAdvice(JoinPoint joinPoint, Throwable ex) {
// ...
}
@AfterReturning(pointcut = "execution(* com.example..*.*(..))", returning = "result")
public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
// ...
}
}
AOP应用场景
AOP在日志管理、性能监控、安全控制等方面有着广泛的应用。例如,在日志管理中,可以通过AOP在方法执行前后记录日志,而在性能监控中,可以记录方法执行的时间。
三、数据持久化
Spring框架提供了强大的数据持久化支持,包括JDBC模板、事务管理和ORM集成。以下是这些技术的详细技术实现细节:
JDBC模板
JDBC模板简化了JDBC编程,通过提供模板方法来执行数据库操作。在Spring中,可以使用JdbcTemplate
类来执行数据库操作:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Map<String, Object>> rows = jdbcTemplate.queryForList("SELECT * FROM table_name");
事务管理
Spring支持声明式事务和编程式事务。声明式事务通过注解或XML配置来实现,而编程式事务则需要编写额外的代码。在Spring中,可以使用@Transactional
注解来声明事务:
@Transactional
public void updateData() {
// ...
}
ORM集成
Spring支持多种ORM框架,如Hibernate。通过集成Hibernate,Spring可以管理会话和事务。在Spring中,可以使用SessionFactory
和Session
来操作Hibernate:
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
try {
session.beginTransaction();
// ...
session.getTransaction().commit();
} finally {
session.close();
}
JPA规范实现
Spring Data JPA提供了一个高度抽象的API,简化了JPA的使用。在Spring中,可以使用@Entity
、@Repository
和@Query
注解来定义实体、仓储和查询:
@Entity
public class User {
@Id
private Long id;
private String name;
// ...
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.name = :name")
List<User> findByName(@Param("name") String name);
}
多数据源配置
Spring支持配置多个数据源,这对于需要连接到多个数据库的应用程序非常有用。在Spring中,可以使用AbstractRoutingDataSource
来实现多数据源路由:
public class DataSourceRouter extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// 根据线程上下文获取数据源名称
return DataSourceContextHolder.getDataSourceType();
}
}
四、Web开发体系
Spring框架提供了全面的Web开发支持,包括MVC架构和RESTful支持。以下是这些技术的详细技术实现细节:
MVC架构组件
Spring MVC框架由控制器(Controller)、视图解析器(ViewResolver)和数据绑定器(DataBinder)等组件组成。在Spring中,可以使用@Controller
注解来定义控制器:
@Controller
public class MyController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, World!");
return "hello";
}
}
数据绑定
数据绑定允许将HTTP请求参数绑定到Java对象。在Spring中,可以使用@RequestParam
、@ModelAttribute
和@RequestBody
等注解来实现数据绑定:
@RequestMapping("/submit")
public String submit(@RequestParam("name") String name, @ModelAttribute("user") User user, @RequestBody User requestUser) {
// ...
}
RESTful支持
Spring MVC支持RESTful风格的应用程序开发。在Spring中,可以使用@RestController
和@RequestMapping
等注解来定义RESTful控制器:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// ...
}
@PostMapping("/")
public User createUser(@RequestBody User user) {
// ...
}
}
异常处理机制
Spring MVC提供了强大的异常处理机制,可以通过控制器、视图或异常处理器来处理异常。在Spring中,可以使用@ExceptionHandler
注解来定义异常处理器:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
// ...
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
文件上传下载
Spring MVC支持文件上传和下载,可以通过MultipartFile
接口和HttpServletResponse
来实现。在Spring中,可以使用@RequestParam("file") MultipartFile file
来接收上传的文件:
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
// ...
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}
五、安全框架
Spring Security是Spring框架的安全框架,提供了认证和授权功能。以下是Spring Security的关键组成部分的详细技术实现细节:
认证流程
Spring Security通过认证流程来验证用户的身份。在Spring Security中,可以使用AuthenticationFilter
来拦截请求并执行认证逻辑:
public class MyAuthenticationFilter extends BasicAuthenticationFilter {
public MyAuthenticationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
// ...
}
}
授权模型
Spring Security使用基于角色的访问控制(RBAC)模型来授权用户。在Spring Security中,可以使用AccessDecisionManager
来决定用户是否有权限访问某个资源:
public class MyAccessDecisionManager implements AccessDecisionManager {
@Override
public void decide(Authentication authentication, Object object, Collection<AccessDecisionVoter<? super Object>> voters) throws AccessDeniedException {
// ...
}
@Override
public boolean supports(Class<?> clazz) {
return true;
}
}
CSRF防护
Spring Security提供了CSRF防护,以防止跨站请求伪造攻击。在Spring Security中,可以使用CsrfTokenRepository
来存储CSRF令牌:
public class HttpSessionCsrfTokenRepository implements CsrfTokenRepository<HttpServletRequest> {
@Override
public CsrfToken generateToken(HttpServletRequest request) {
// ...
}
@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
// ...
}
@Override
public CsrfToken obtainToken(HttpServletRequest request) {
// ...
}
@Override
public void removeToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
// ...
}
}
OAuth2集成
Spring Security支持OAuth2协议,允许用户通过第三方服务进行认证。在Spring Security中,可以使用OAuth2ClientContext
来存储OAuth2令牌:
public class MyOAuth2ClientContext implements OAuth2ClientContext {
@Override
public void setAccessToken(OAuth2AccessToken accessToken) {
// ...
}
@Override
public OAuth2AccessToken getAccessToken() {
// ...
}
// ...
}
方法级安全
Spring Security允许在方法级别上配置安全性,使得安全配置更加灵活。在Spring Security中,可以使用@PreAuthorize
和@PostAuthorize
注解来定义方法级别的安全性:
public class MyController {
@PreAuthorize("hasRole('ADMIN')")
public void adminMethod() {
// ...
}
@PostAuthorize("hasRole('USER')")
public void userMethod() {
// ...
}
}
六、高级特性
Spring框架还提供了许多高级特性,包括事件发布/监听机制、SpEL表达式、响应式编程和缓存抽象。以下是这些特性的详细技术实现细节:
事件发布/监听机制
Spring允许通过事件发布/监听机制来通知应用程序中的其他组件。在Spring中,可以使用ApplicationEvent
和ApplicationListener
来定义事件和监听器:
public class MyApplicationEvent extends ApplicationEvent {
public MyApplicationEvent(Object source) {
super(source);
}
}
@Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {
@Override
public void onApplicationEvent(MyApplicationEvent event) {
// ...
}
}
SpEL表达式
Spring表达式语言(SpEL)允许在运行时动态地评估表达式。在Spring中,可以使用ExpressionParser
来解析SpEL表达式:
ExpressionParser parser = new SpELExpressionParser();
Expression expression = parser.parseExpression("'Hello, World!'");
String result = (String) expression.getValue();
响应式编程(WebFlux)
Spring WebFlux是一个响应式Web框架,允许以非阻塞的方式处理HTTP请求。在Spring WebFlux中,可以使用Flux
和Mono
来表示异步的数据流:
public class MyWebFluxController {
@GetMapping("/stream")
public Flux<String> stream() {
return Flux.fromStream(Stream.generate(() -> "Hello, World!"));
}
}
测试框架集成
Spring支持多种测试框架,如JUnit和TestNG,使得单元测试和集成测试变得容易。在Spring中,可以使用@SpringBootTest
注解来启动应用程序上下文,并执行测试:
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void testMyService() {
// ...
}
}
缓存抽象
Spring提供了缓存抽象,允许以编程方式或声明式方式配置缓存。在Spring中,可以使用@EnableCaching
注解来启用缓存支持,并使用@Cacheable
、@CachePut
和@CacheEvict
注解来定义缓存操作:
@EnableCaching
public class MyCacheConfig {
// ...
}
@Service
public class MyService {
@Cacheable("myCache")
public String getSomething() {
// ...
}
@CachePut("myCache")
public String updateSomething() {
// ...
}
@CacheEvict("myCache")
public void deleteSomething() {
// ...
}
}
七、Spring Boot生态
Spring Boot简化了Spring应用程序的配置和管理。以下是Spring Boot生态的关键组成部分的详细技术实现细节:
自动配置原理
Spring Boot通过自动配置原理自动配置Spring应用程序。在Spring Boot中,可以通过条件注解和配置属性来启用自动配置:
@Configuration
@ConditionalOnClass(DataSource.class)
public class DataSourceConfig {
// ...
}
Starter机制
Spring Boot的Starter依赖项提供了自动配置所需的库。在Spring Boot中,可以通过添加相应的Starter依赖项来启用自动配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Actuator监控
Spring Boot Actuator允许监控和管理Spring应用程序。在Spring Boot中,可以通过添加spring-boot-starter-actuator
依赖项来启用Actuator支持:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置文件体系
Spring Boot使用配置文件来管理应用程序的配置,包括application.properties
和application.yml
。在Spring Boot中,可以通过配置文件来指定应用程序的属性值:
# application.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
# application.yml
server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: root
通过以上对Spring框架中关键知识点的详细描述,我们可以看到这些知识点是如何相互关联和相互支持的。Spring框架的强大之处在于它提供了一种模块化和可扩展的方式来构建应用程序,同时保持了代码的清晰和可维护性。
博主分享
📥博主的人生感悟和目标
📙经过多年在优快云创作上千篇文章的经验积累,我已经拥有了不错的写作技巧。同时,我还与清华大学出版社签下了四本书籍的合约,并将陆续出版。
- 《Java项目实战—深入理解大型互联网企业通用技术》基础篇的购书链接:https://item.jd.com/14152451.html
- 《Java项目实战—深入理解大型互联网企业通用技术》基础篇繁体字的购书链接:http://product.dangdang.com/11821397208.html
- 《Java项目实战—深入理解大型互联网企业通用技术》进阶篇的购书链接:https://item.jd.com/14616418.html
- 《Java项目实战—深入理解大型互联网企业通用技术》架构篇待上架
- 《解密程序员的思维密码--沟通、演讲、思考的实践》购书链接:https://item.jd.com/15096040.html
面试备战资料
八股文备战
场景 | 描述 | 链接 |
---|---|---|
时间充裕(25万字) | Java知识点大全(高频面试题) | Java知识点大全 |
时间紧急(15万字) | Java高级开发高频面试题 | Java高级开发高频面试题 |
理论知识专题(图文并茂,字数过万)
技术栈 | 链接 |
---|---|
RocketMQ | RocketMQ详解 |
Kafka | Kafka详解 |
RabbitMQ | RabbitMQ详解 |
MongoDB | MongoDB详解 |
ElasticSearch | ElasticSearch详解 |
Zookeeper | Zookeeper详解 |
Redis | Redis详解 |
MySQL | MySQL详解 |
JVM | JVM详解 |
集群部署(图文并茂,字数过万)
技术栈 | 部署架构 | 链接 |
---|---|---|
MySQL | 使用Docker-Compose部署MySQL一主二从半同步复制高可用MHA集群 | Docker-Compose部署教程 |
Redis | 三主三从集群(三种方式部署/18个节点的Redis Cluster模式) | 三种部署方式教程 |
RocketMQ | DLedger高可用集群(9节点) | 部署指南 |
Nacos+Nginx | 集群+负载均衡(9节点) | Docker部署方案 |
Kubernetes | 容器编排安装 | 最全安装教程 |
开源项目分享
项目名称 | 链接地址 |
---|---|
高并发红包雨项目 | https://gitee.com/java_wxid/red-packet-rain |
微服务技术集成demo项目 | https://gitee.com/java_wxid/java_wxid |
管理经验
【公司管理与研发流程优化】针对研发流程、需求管理、沟通协作、文档建设、绩效考核等问题的综合解决方案:https://download.youkuaiyun.com/download/java_wxid/91148718
希望各位读者朋友能够多多支持!
现在时代变了,信息爆炸,酒香也怕巷子深,博主真的需要大家的帮助才能在这片海洋中继续发光发热,所以,赶紧动动你的小手,点波关注❤️,点波赞👍,点波收藏⭐,甚至点波评论✍️,都是对博主最好的支持和鼓励!
- 💂 博客主页: Java程序员廖志伟
- 👉 开源项目:Java程序员廖志伟
- 🌥 哔哩哔哩:Java程序员廖志伟
- 🎏 个人社区:Java程序员廖志伟
- 🔖 个人微信号:
SeniorRD
🔔如果您需要转载或者搬运这篇文章的话,非常欢迎您私信我哦~