Skip to content

Spring Boot 集成

将 LCGYL Framework 集成到 Spring Boot 项目中。

快速开始

1. 添加依赖

pom.xml 中添加:

xml
<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
    <!-- LCGYL Spring Boot Starter -->
    <dependency>
        <groupId>com.lcgyl</groupId>
        <artifactId>lcgyl-framework-spring</artifactId>
        <version>${lcgyl.version}</version>
    </dependency>
    
    <!-- 需要的插件 -->
    <dependency>
        <groupId>com.lcgyl</groupId>
        <artifactId>lcgyl-web-plugin</artifactId>
    </dependency>
    <dependency>
        <groupId>com.lcgyl</groupId>
        <artifactId>lcgyl-cache-plugin</artifactId>
    </dependency>
</dependencies>

或在 build.gradle 中添加:

gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'com.lcgyl:lcgyl-framework-spring'
    implementation 'com.lcgyl:lcgyl-web-plugin'
    implementation 'com.lcgyl:lcgyl-cache-plugin'
}

2. 启用 LCGYL

在启动类上添加 @EnableLcgyl 注解:

java
@SpringBootApplication
@EnableLcgyl
public class Application {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3. 配置插件

application.yml 中配置:

yaml
lcgyl:
  # 启用的插件
  plugins:
    web:
      enabled: true
      server:
        port: 8080
        contextPath: /api
    data:
      enabled: true
      datasource:
        url: jdbc:mysql://localhost:3306/db
        username: root
        password: password

使用插件

Web 插件

创建控制器

java
@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
    
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.save(user);
    }
}

配置 Web

yaml
lcgyl:
  plugins:
    web:
      enabled: true
      server:
        port: 8080
        contextPath: /api
        # 静态资源
        static-locations:
          - classpath:/static/
          - classpath:/public/
        # CORS 配置
        cors:
          allowed-origins: "*"
          allowed-methods: GET,POST,PUT,DELETE

数据访问插件

创建 Repository

java
@Repository
public class UserRepository {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public Optional<User> findById(Long id) {
        String sql = "SELECT * FROM users WHERE id = ?";
        return jdbcTemplate.queryForOptional(sql, User.class, id);
    }
    
    @Transactional
    public User save(User user) {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        Long id = jdbcTemplate.insert(sql, user.getName(), user.getEmail());
        user.setId(id);
        return user;
    }
}

配置数据源

yaml
lcgyl:
  plugins:
    data:
      enabled: true
      # 主数据源
      datasource:
        url: jdbc:mysql://localhost:3306/db
        username: root
        password: password
        driver-class-name: com.mysql.cj.jdbc.Driver
        # 连接池配置
        hikari:
          maximum-pool-size: 20
          minimum-idle: 5
          connection-timeout: 30000
      
      # 多数据源
      datasources:
        secondary:
          url: jdbc:mysql://localhost:3306/db2
          username: root
          password: password

消息队列插件

发送消息

java
@Service
public class OrderService {
    
    @Autowired
    private MessageProducer messageProducer;
    
    public void createOrder(Order order) {
        // 保存订单
        orderRepository.save(order);
        
        // 发送消息
        messageProducer.send("order.created", order);
    }
}

接收消息

java
@Component
public class OrderListener {
    
    @MessageListener(topic = "order.created")
    public void onOrderCreated(Order order) {
        // 处理订单创建事件
        System.out.println("订单已创建: " + order.getId());
    }
}

配置消息队列

yaml
lcgyl:
  plugins:
    messaging:
      enabled: true
      # 消息队列类型
      type: rabbitmq
      # RabbitMQ 配置
      rabbitmq:
        host: localhost
        port: 5672
        username: guest
        password: guest
        virtual-host: /

安全插件

配置安全

java
@Configuration
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain securityFilterChain() {
        return SecurityFilterChain.builder()
            .authorizeRequests(auth -> auth
                .antMatchers("/public/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .defaultSuccessUrl("/")
            )
            .build();
    }
}

使用认证

java
@RestController
public class AuthController {
    
    @Autowired
    private AuthenticationService authService;
    
    @PostMapping("/login")
    public LoginResponse login(@RequestBody LoginRequest request) {
        String token = authService.authenticate(
            request.getUsername(),
            request.getPassword()
        );
        return new LoginResponse(token);
    }
}

配置安全

yaml
lcgyl:
  plugins:
    security:
      enabled: true
      # JWT 配置
      jwt:
        secret: your-secret-key
        expiration: 86400000
      # OAuth2 配置
      oauth2:
        client-id: your-client-id
        client-secret: your-client-secret

自动配置

LCGYL Spring Boot Starter 提供自动配置:

自动配置的组件

  • JdbcTemplate:数据库访问模板
  • TransactionManager:事务管理器
  • MessageProducer:消息生产者
  • MessageConsumer:消息消费者
  • AuthenticationService:认证服务
  • CacheManager:缓存管理器

条件配置

java
@Configuration
@ConditionalOnProperty(name = "lcgyl.plugins.web.enabled", havingValue = "true")
public class WebAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean
    public WebServer webServer() {
        return new NettyWebServer();
    }
}

配置属性

完整配置示例

yaml
lcgyl:
  # 插件配置
  plugins:
    # Web 插件
    web:
      enabled: true
      server:
        port: 8080
        contextPath: /api
        static-locations:
          - classpath:/static/
        cors:
          enabled: true
          allowed-origins: "*"
    
    # 数据访问插件
    data:
      enabled: true
      datasource:
        url: jdbc:mysql://localhost:3306/db
        username: root
        password: password
        hikari:
          maximum-pool-size: 20
          minimum-idle: 5
    
    # 消息队列插件
    messaging:
      enabled: true
      type: rabbitmq
      rabbitmq:
        host: localhost
        port: 5672
    
    # 安全插件
    security:
      enabled: true
      jwt:
        secret: your-secret-key
        expiration: 86400000
    
    # 缓存插件
    cache:
      enabled: true
      type: redis
      redis:
        host: localhost
        port: 6379
    
    # 任务调度插件
    scheduling:
      enabled: true
      pool-size: 10

与 Spring 功能对比

功能SpringLCGYL说明
IoC/DI使用 Spring 容器
事务管理兼容 Spring 事务
数据访问JdbcTemplateJdbcTemplate增强版
消息队列Spring AMQPLCGYL Messaging统一抽象
缓存Spring CacheLCGYL Cache更多特性
安全Spring SecurityLCGYL Security简化配置
任务调度@Scheduled@Scheduled兼容

最佳实践

1. 使用 Spring 注解

java
// ✅ 推荐:使用 Spring 注解
@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Transactional
    public User save(User user) {
        return userRepository.save(user);
    }
}

2. 配置外部化

yaml
# application.yml
lcgyl:
  plugins:
    data:
      datasource:
        url: ${DB_URL:jdbc:mysql://localhost:3306/db}
        username: ${DB_USERNAME:root}
        password: ${DB_PASSWORD:password}

3. 环境配置

yaml
# application-dev.yml
lcgyl:
  plugins:
    web:
      server:
        port: 8080

# application-prod.yml
lcgyl:
  plugins:
    web:
      server:
        port: 80

4. 健康检查

java
@Component
public class LcgylHealthIndicator implements HealthIndicator {
    
    @Override
    public Health health() {
        // 检查 LCGYL 插件状态
        return Health.up()
            .withDetail("plugins", "all running")
            .build();
    }
}

常见问题

Q: 如何禁用某个插件?

yaml
lcgyl:
  plugins:
    web:
      enabled: false

Q: 如何自定义配置?

java
@Configuration
public class CustomConfig {
    
    @Bean
    public JdbcTemplate customJdbcTemplate(DataSource dataSource) {
        JdbcTemplate template = new JdbcTemplate(dataSource);
        template.setQueryTimeout(30);
        return template;
    }
}

Q: 如何与现有 Spring 项目集成?

  1. 添加 LCGYL 依赖
  2. 添加 @EnableLcgyl 注解
  3. 配置需要的插件
  4. 逐步迁移功能

下一步

Released under the Apache License 2.0