Spring框架广泛应用了多种设计模式,以实现其灵活性、可扩展性和可维护性。以下是一些在Spring中常见的设计模式及其应用示例:
@Service public class SingletonService { // 单例Bean的实现 }
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); MyService myService = context.getBean(MyService.class);
@Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("Executing: " + joinPoint.getSignature().getName()); } }
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()); } }
public class CustomApplicationListener implements ApplicationListener { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("Application context has been initialized or refreshed."); } }
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); } }
public class CustomAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 自定义认证逻辑 return authentication; } @Override public boolean supports(Class> authentication) { return true; } }
8. 适配器模式(Adapter Pattern)
Spring MVC中的HandlerAdapter接口允许不同的控制器实现以统一的方式被调用,这是适配器模式的体现。
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; } }