Spring框架中使用的设计模式详解

在这里插入图片描述

Spring框架是一个广泛使用的Java企业级应用框架,其内部大量使用了各种设计模式来提高灵活性、可扩展性和可维护性。下面我将详细介绍Spring中应用的主要设计模式。

1. 工厂模式(Factory Pattern)

1.1 BeanFactory和ApplicationContext

Spring的核心容器本质上是一个工厂模式的实现,通过BeanFactoryApplicationContext接口创建和管理bean对象。

// 工厂模式示例
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Object bean = context.getBean("beanName");

1.2 静态工厂方法

Spring支持通过静态工厂方法创建bean:

<bean id="clientService" 
      class="com.example.ClientService"
      factory-method="createInstance"/>

2. 单例模式(Singleton Pattern)

Spring默认使用单例模式管理bean:

@Configuration
public class AppConfig {
    @Bean
    @Scope("singleton") // 默认就是单例,可省略
    public MyBean myBean() {
        return new MyBean();
    }
}

3. 原型模式(Prototype Pattern)

当需要每次获取新实例时:

@Bean
@Scope("prototype")
public MyBean myBean() {
    return new MyBean();
}

4. 代理模式(Proxy Pattern)

4.1 AOP实现

Spring AOP使用JDK动态代理或CGLIB实现代理模式:

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

4.2 @Transactional

事务管理也是通过代理实现的:

@Service
public class UserService {
    @Transactional
    public void createUser(User user) {
        // 数据库操作
    }
}

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

5.1 JdbcTemplate

Spring的JdbcTemplate等模板类:

jdbcTemplate.query("SELECT * FROM users", 
    (rs, rowNum) -> new User(
        rs.getLong("id"),
        rs.getString("name"))
);

5.2 RestTemplate

restTemplate.getForObject("http://example.com/users/{id}", User.class, userId);

6. 观察者模式(Observer Pattern)

Spring的事件机制:

// 定义事件
public class MyEvent extends ApplicationEvent {
    public MyEvent(Object source) {
        super(source);
    }
}

// 发布事件
applicationContext.publishEvent(new MyEvent(this));

// 监听事件
@Component
public class MyEventListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent event) {
        // 处理事件
    }
}

7. 策略模式(Strategy Pattern)

7.1 资源访问

Spring的资源访问接口Resource

Resource resource = new ClassPathResource("config.xml");
// 或
Resource resource = new FileSystemResource("/conf/config.xml");

7.2 事务管理

不同的事务管理策略:

@Configuration
@EnableTransactionManagement
public class PersistenceConfig {
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        return new JpaTransactionManager(emf); // JPA策略
        // 或 return new DataSourceTransactionManager(dataSource()); // JDBC策略
    }
}

8. 装饰者模式(Decorator Pattern)

8.1 HttpServletRequestWrapper

Spring MVC中的请求包装:

public class MyRequestWrapper extends HttpServletRequestWrapper {
    public MyRequestWrapper(HttpServletRequest request) {
        super(request);
    }
    
    @Override
    public String getParameter(String name) {
        // 修改参数逻辑
        return super.getParameter(name);
    }
}

8.2 Bean装饰

通过BeanPostProcessor装饰bean:

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        // 对bean进行装饰
        return bean;
    }
}

9. 适配器模式(Adapter Pattern)

9.1 HandlerAdapter

Spring MVC中的处理器适配器:

// DispatcherServlet通过HandlerAdapter调用Controller
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
ModelAndView mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

9.2 AOP适配器

AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
Advisor[] advisors = registry.getAdvisors(advisor);

10. 责任链模式(Chain of Responsibility Pattern)

10.1 过滤器链

Spring Security的过滤器链:

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
            FilterChain chain) throws IOException, ServletException {
        // 前置处理
        chain.doFilter(request, response); // 传递给下一个过滤器
        // 后置处理
    }
}

10.2 HandlerInterceptor

Spring MVC的拦截器链:

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
            Object handler) throws Exception {
        // 返回true继续执行链,false中断
        return true;
    }
}

11. 建造者模式(Builder Pattern)

Spring中的建造者模式应用:

// Spring Security配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .permitAll();
    }
}

12. 组合模式(Composite Pattern)

Spring缓存抽象中的组合使用:

@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        CompositeCacheManager cacheManager = new CompositeCacheManager();
        cacheManager.setCacheManagers(Arrays.asList(
            new ConcurrentMapCacheManager("cache1"),
            new EhCacheCacheManager() // 可以组合多个缓存实现
        ));
        return cacheManager;
    }
}

13. 状态模式(State Pattern)

Spring状态机(Spring Statemachine):

@Configuration
@EnableStateMachine
public class StateMachineConfig extends StateMachineConfigurerAdapter<String, String> {
    @Override
    public void configure(StateMachineStateConfigurer<String, String> states)
            throws Exception {
        states
            .withStates()
                .initial("SI")
                .state("S1")
                .end("SF");
    }
}

14. 访问者模式(Visitor Pattern)

Spring表达式语言(SpEL)中的访问者模式:

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'.concat('!')");
String message = (String) exp.getValue();

总结

Spring框架几乎涵盖了所有的GoF设计模式,这些模式的灵活运用使得Spring具有极高的扩展性和适应性。理解这些设计模式在Spring中的应用,不仅能帮助我们更好地使用Spring,也能提升我们的架构设计能力。

设计模式Spring中的应用场景
工厂模式BeanFactory, ApplicationContext
单例模式Spring Bean的默认作用域
原型模式@Scope(“prototype”)
代理模式AOP, @Transactional
模板方法JdbcTemplate, RestTemplate
观察者ApplicationEvent机制
策略资源访问, 事务管理
装饰者BeanPostProcessor, 请求包装
适配器HandlerAdapter
责任链过滤器链, 拦截器链
建造者Security配置, BeanDefinitionBuilder
组合CompositeCacheManager
状态Spring Statemachine
访问者SpEL表达式解析

Spring框架的成功很大程度上归功于这些设计模式的合理运用,它们共同构成了Spring灵活、可扩展的架构基础。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北辰alk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值