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灵活、可扩展的架构基础。
在这里插入图片描述