Spring中用了哪些设计模式?

Spring框架广泛应用了多种设计模式,以实现其灵活性、可扩展性和可维护性。以下是一些在Spring中常见的设计模式及其应用示例:

1. 单例模式(Singleton Pattern)

Spring中的Bean默认都是单例的,这意味着在整个应用上下文中,每个Bean定义只有一个实例。

java 复制代码
@Service
public class SingletonService {
    // 单例Bean的实现
}

2. 工厂模式(Factory Pattern)

Spring使用BeanFactory和ApplicationContext接口来创建和管理Bean实例,这是工厂模式的典型应用。

java 复制代码
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyService myService = context.getBean(MyService.class);

3. 代理模式(Proxy Pattern)

Spring AOP(面向切面编程)通过代理模式实现,可以在不修改原有代码的情况下增强功能。

java 复制代码
@Aspect
@Component
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("Executing: " + joinPoint.getSignature().getName());
    }
}

4. 模板方法模式(Template Method Pattern)

Spring提供了多种模板类,如JdbcTemplate、RestTemplate等,这些模板类定义了一套固定的流程,但允许子类重写某些步骤。

java 复制代码
public class JdbcCustomerDao {
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public Customer getCustomerById(int id) {
        return jdbcTemplate.queryForObject("SELECT * FROM customers WHERE id = ?", new Object[]{id}, new CustomerRowMapper());
    }
}

5. 观察者模式(Observer Pattern)

Spring的事件机制基于观察者模式,允许应用组件监听和响应特定事件。

java 复制代码
public class CustomApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("Application context has been initialized or refreshed.");
    }
}

6. 策略模式(Strategy Pattern)

Spring的依赖注入机制允许开发者灵活地选择和切换不同的实现策略。

java 复制代码
public interface PaymentStrategy {
    void pay(int amount);
}

@Service
public class CreditCardPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paid with credit card: " + amount);
    }
}

@Service
public class PayPalPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paid with PayPal: " + amount);
    }
}

7. 装饰器模式(Decorator Pattern)

Spring Security中的认证和授权机制使用了装饰器模式,通过层层包装来增强功能。

java 复制代码
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 自定义认证逻辑
        return authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
  1. 适配器模式(Adapter Pattern)

Spring MVC中的HandlerAdapter接口允许不同的控制器实现以统一的方式被调用,这是适配器模式的体现。

java 复制代码
public class SimpleControllerHandlerAdapter implements HandlerAdapter {
    @Override
    public boolean supports(Object handler) {
        return (handler instanceof Controller);
    }

    @Override
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return ((Controller) handler).handleRequest(request, response);
    }

    @Override
    public long getLastModified(HttpServletRequest request, Object handler) {
        return -1;
    }
}
相关推荐
qmx_0725 分钟前
HTB-Jerry(tomcat war文件、msfvenom)
java·web安全·网络安全·tomcat
为风而战33 分钟前
IIS+Ngnix+Tomcat 部署网站 用IIS实现反向代理
java·tomcat
技术无疆2 小时前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
架构文摘JGWZ5 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
拾光师6 小时前
spring获取当前request
java·后端·spring
aPurpleBerry6 小时前
neo4j安装启动教程+对应的jdk配置
java·neo4j
我是苏苏6 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
xujinwei_gingko7 小时前
Spring IOC容器Bean对象管理-Java Config方式
java·spring
2301_789985947 小时前
Java语言程序设计基础篇_编程练习题*18.29(某个目录下的文件数目)
java·开发语言·学习
IT学长编程7 小时前
计算机毕业设计 教师科研信息管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·毕业设计·springboot·毕业论文·计算机毕业设计选题·计算机毕业设计开题报告·教师科研管理系统