SpringBoot項(xiàng)目開(kāi)發(fā)的智慧錦囊:技巧與應(yīng)用一網(wǎng)打盡
環(huán)境:SpringBoot2.7.16
1. Bean生命周期
使用@PostConstruct和@PreDestroy注解在Bean的生命周期特定階段執(zhí)行代碼,也可以通過(guò)分別實(shí)現(xiàn)InitializingBean和DisposableBean接口。
public class Bean1 {
@PostConstruct
public void init() {}
@PreDestroy
public void destroy() {}
}
public class Bean2 implements InitializingBean, DisposableBean {
public void afterPropertiesSet() {}
public void destroy() {}
}
2. 依賴注入
- 使用@Autowired注解自動(dòng)裝配Bean。
- 使用@Qualifier注解解決自動(dòng)裝配時(shí)的歧義。
- 使用@Resource或@Inject注解進(jìn)行依賴注入。
@Component
public class Service {
@Autowired
private Dog dog ;
@Resource
private Cat cat ;
@Autowired
@Qualifier("d") // 指定beanName
private Person person ;
@Inject
private DAO dao ;
}
以上都是基于屬性的注入,官方建議使用構(gòu)造函數(shù)注入
@Component
public class Service {
private final Dog dog ;
private final Cat cat ;
public Service(Dog dog, Cat cat) {
this.dog = dog ;
this.cat = cat ;
}
}
3. 基于注解配置
- 使用Java Config替代傳統(tǒng)的XML配置。
- 利用Profile或是各種Conditional功能為不同環(huán)境提供不同的配置。
@Configuration
public class AppConfig {
@Bean
public PersonService personService(PersonDAO dao) {
return new PersonService(dao) ;
}
@Bean
@Profile("test")
public PersonDAO personDAOTest() {
return new PersonDAOTest() ;
}
@Bean
@Profile("prod")
public PersonDAO personDAOProd() {
return new PersonDAOProd() ;
}
}
上面的@Profile會(huì)根據(jù)當(dāng)前環(huán)境配置的spring.profiles.active屬性決定創(chuàng)建那個(gè)對(duì)象。
4. 條件配置Bean
- 使用@Conditional注解根據(jù)條件創(chuàng)建Bean。
- 實(shí)現(xiàn)Condition接口自定義條件。
@Bean
// 當(dāng)前環(huán)境沒(méi)有CsrfFilter Bean
@ConditionalOnMissingBean(CsrfFilter.class)
// 配置文件中的pack.csrf.enabled=true或者沒(méi)有配置
@ConditionalOnProperty(prefix = "pack.csrf", name = "enabled", matchIfMissing = true)
public CsrfFilter csrfFilter() {
return new CsrfFilter ();
}
自定義條件配置
public class PackCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// ...
}
}
// 使用
@Component
@Conditional({PackCondition.class})
public class PersonServiceTest {}
5. 事件監(jiān)聽(tīng)
- 使用Spring的事件機(jī)制進(jìn)行組件間的通信。
- 創(chuàng)建自定義事件和應(yīng)用監(jiān)聽(tīng)器。
@Component
public class OrderListener implements ApplicationListener<OrderEvent> {
public void onApplicationEvent(OrderEvent event) {
// ...
}
}
// 也可以通過(guò)注解的方式
@Configuration
public class EventManager {
@EventListener
public void order(OrderEvent event) {}
}
事件詳細(xì)使用,查看《利用Spring事件機(jī)制:打造可擴(kuò)展和可維護(hù)的應(yīng)用》。
6. 切面編程(AOP)
- 使用AOP實(shí)現(xiàn)橫切關(guān)注點(diǎn),如日志、權(quán)限、事務(wù)管理等。
- 定義切面、通知、切入點(diǎn)等。
@Component
@Aspect
public class AuthAspect {
@Pointcut("execution(public * com.pack..*.*(..))")
private void auth() {}
@Before("auth()")
public void before() {
}
}
7. 計(jì)劃任務(wù)
- 使用@Scheduled注解輕松實(shí)現(xiàn)定時(shí)任務(wù)。
- 配置TaskScheduler進(jìn)行更復(fù)雜的任務(wù)調(diào)度。
public class SchedueService {
@Scheduled(cron = "*/2 * * * * *")
public void task() {
System.out.printf("%s: %d - 任務(wù)調(diào)度%n", Thread.currentThread().getName(), System.currentTimeMillis()) ;
}
}
每隔2s執(zhí)行任務(wù)。
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(1) ;
threadPoolTaskScheduler.initialize() ;
return threadPoolTaskScheduler ;
}
自定義線程池任務(wù)調(diào)度。
8. 數(shù)據(jù)訪問(wèn)
- 用Spring Data JPA簡(jiǎn)化數(shù)據(jù)庫(kù)訪問(wèn)層的開(kāi)發(fā)。
- 利用Spring Data Repositories的聲明式方法實(shí)現(xiàn)CRUD操作。
public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {
}
通過(guò)繼承JapRepository等類就可以直接對(duì)數(shù)據(jù)庫(kù)進(jìn)行CRUD操作了。
@Service
public class OrderDomainServiceImpl implements OrderDomainService {
private final OrderRepository orderRepository;
public OrderDomainServiceImpl(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
// CRUD操作
}
OrderRepository接口提供了如下方法,我們可以直接的調(diào)用
圖片
10. 緩存使用
- 使用Spring Cache抽象進(jìn)行緩存操作。
- 集成第三方緩存庫(kù),如EhCache、Redis等。
public class UserService {
@Cacheable(cacheNames = "users", key = "#id")
public User queryUserById(Integer id) {
System.out.println("查詢操作") ;
return new User() ;
}
@CacheEvict(cacheNames = "users", key = "#user.id")
public void update(User user) {
System.out.println("更新操作") ;
}
}
@EnableCaching
@Configuration
public class Config {
// 配置基于內(nèi)存的緩存管理器;你也可以使用基于redis的實(shí)現(xiàn)
@Bean
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
return cacheManager ;
}
}
11.異常處理
- 使用@ControllerAdvice和@ExceptionHandler全局處理異常。
- 定義統(tǒng)一的異常響應(yīng)格式。
@RestControllerAdvice
public class PackControllerAdvice {
@ExceptionHandler({Exception.class})
public Object error(Exception e) {
Map<String, Object> errors = new HashMap<>() ;
errors.put("error", e.getMessage()) ;
return errors ;
}
}
當(dāng)應(yīng)用發(fā)生異常后會(huì)統(tǒng)一的由上面的類進(jìn)行處理。
12. 安全管理
集成Spring Security進(jìn)行身份驗(yàn)證和授權(quán)。通過(guò)引入spring security進(jìn)行簡(jiǎn)單的配置就能非常方便的管理應(yīng)用的權(quán)限控制。
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {
@Bean
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable() ;
http.authorizeRequests().antMatchers("/*.html").permitAll() ;
http.authorizeRequests().antMatchers("/customers/**").hasAnyRole("CUSTOM") ;
http.authorizeRequests().antMatchers("/orders/**").hasAnyRole("ORDER") ;
http.authorizeRequests().anyRequest().authenticated() ;
http.formLogin() ;
DefaultSecurityFilterChain chain = http.build();
return chain ;
}
}
注意:Spring Security從5.7?開(kāi)始建議使用SecurityFilterChain方式配置授權(quán)規(guī)則。
13. SpEL表達(dá)式
利用Spring Expression Language (SpEL)進(jìn)行表達(dá)式求值,動(dòng)態(tài)調(diào)用bean等等功能。
詳細(xì)查看下面文章,這篇文章詳細(xì)的介紹了SpEL表達(dá)式的應(yīng)用。
14. 配置管理
- 使用Spring Cloud Config實(shí)現(xiàn)配置中心化管理。
- 集成Spring Cloud Bus實(shí)現(xiàn)配置動(dòng)態(tài)更新。
我們項(xiàng)目中應(yīng)該很少使用上面Spring 原生的 Config?,F(xiàn)在大多使用的nacos或者consul。
15. 性能監(jiān)控
- 集成Spring Boot Admin進(jìn)行微服務(wù)監(jiān)控。
- 使用Metrics或Micrometer進(jìn)行應(yīng)用性能指標(biāo)收集。
16. 微服務(wù)組件
- 利用Spring Cloud構(gòu)建微服務(wù)架構(gòu)。
- 使用Feign聲明式地調(diào)用其他微服務(wù)。
- 集成Hystrix實(shí)現(xiàn)熔斷和降級(jí)。
以上內(nèi)容查看下面幾篇文章,分別詳細(xì)的介紹了每種組件的應(yīng)用。