Skip to content

常见问题解答 - Spring 集成

将 LCGYL Framework 与 Spring Boot 集成时的常见问题。

如果你在独立使用 LCGYL Framework,请查看 独立使用常见问题

安装和配置

Q: 需要什么版本的 Spring Boot?

A: LCGYL Framework 1.0.x 需要 Spring Boot 3.3.x 或更高版本。

xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.5</version>
</parent>

Q: 如何启用 LCGYL?

A: 在 Spring Boot 主类上添加 @EnableLcgyl 注解:

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

Q: 如何配置插件?

A: 在 application.yml 中配置:

yaml
lcgyl:
  plugins:
    web:
      enabled: true
      server:
        port: 8080
    data:
      enabled: true
      datasource:
        url: jdbc:mysql://localhost:3306/db

依赖注入

Q: 应该使用 @Autowired 还是 @Inject?

A: 两者都可以,但推荐使用 Spring 的 @Autowired

java
// ✅ 推荐:使用 @Autowired
@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
}

// ✅ 也可以:使用 @Inject
@Service
public class UserService {
    
    @Inject
    private UserRepository userRepository;
}

Q: LCGYL 组件能注入 Spring Bean 吗?

A: 可以,LCGYL 与 Spring 容器完全集成:

java
@Service
public class OrderService {
    
    // Spring Bean
    @Autowired
    private UserService userService;
    
    // LCGYL Bean
    @Inject
    private MessageProducer messageProducer;
}

Q: Spring Bean 能注入 LCGYL 组件吗?

A: 可以,LCGYL 组件会自动注册到 Spring 容器:

java
@Service
public class SpringService {
    
    @Autowired
    private LcgylComponent lcgylComponent;  // LCGYL 组件
}

事务管理

Q: 应该使用哪个 @Transactional?

A: 使用 Spring 的 @Transactional

java
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    
    @Transactional
    public User createUser(User user) {
        return userRepository.save(user);
    }
}

Q: LCGYL 事务和 Spring 事务冲突吗?

A: 不冲突,LCGYL 会自动使用 Spring 的事务管理器:

java
@Service
public class OrderService {
    
    // Spring 事务
    @Transactional
    public void createOrder(Order order) {
        orderRepository.save(order);
        
        // LCGYL 组件也在同一事务中
        inventoryService.decreaseStock(order.getItems());
    }
}

Q: 如何使用编程式事务?

A: 使用 Spring 的 TransactionTemplate

java
@Service
public class OrderService {
    
    @Autowired
    private TransactionTemplate transactionTemplate;
    
    public Order createOrder(Order order) {
        return transactionTemplate.execute(status -> {
            // 事务操作
            return orderRepository.save(order);
        });
    }
}

数据访问

Q: 可以同时使用 Spring Data JPA 和 LCGYL JDBC 吗?

A: 可以,它们可以共存:

java
// Spring Data JPA
@Repository
public interface UserJpaRepository extends JpaRepository<User, Long> {
}

// LCGYL JDBC
@Repository
public class UserJdbcRepository {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public List<User> complexQuery() {
        // 复杂查询
    }
}

// Service 层混合使用
@Service
public class UserService {
    
    @Autowired
    private UserJpaRepository jpaRepository;
    
    @Autowired
    private UserJdbcRepository jdbcRepository;
}

Q: 如何配置多数据源?

A: 在 application.yml 中配置:

yaml
lcgyl:
  plugins:
    data:
      datasources:
        primary:
          url: jdbc:mysql://localhost:3306/db1
          username: root
          password: password
        secondary:
          url: jdbc:mysql://localhost:3306/db2
          username: root
          password: password

然后在代码中使用:

java
@Configuration
public class DataSourceConfig {
    
    @Bean
    @Primary
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create()
            .url("jdbc:mysql://localhost:3306/db1")
            .build();
    }
    
    @Bean
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create()
            .url("jdbc:mysql://localhost:3306/db2")
            .build();
    }
}

消息队列

Q: 可以同时使用 Spring AMQP 和 LCGYL Messaging 吗?

A: 可以,但不推荐。建议选择其中一个:

java
// 如果使用 Spring AMQP
@RabbitListener(queues = "order.queue")
public void handleOrder(Order order) {
    // 处理订单
}

// 如果使用 LCGYL Messaging
@MessageListener(topic = "order.created")
public void onOrderCreated(Order order) {
    // 处理订单
}

Q: 如何在 Spring 中发送 LCGYL 消息?

A: 注入 MessageProducer

java
@Service
public class OrderService {
    
    @Autowired
    private MessageProducer messageProducer;
    
    public void createOrder(Order order) {
        orderRepository.save(order);
        messageProducer.send("order.created", order);
    }
}

安全

Q: 可以同时使用 Spring Security 和 LCGYL Security 吗?

A: 可以,但不推荐。建议选择其中一个:

java
// 如果使用 Spring Security
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) {
        return http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .build();
    }
}

// 如果使用 LCGYL Security
@Configuration
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain securityFilterChain() {
        return SecurityFilterChain.builder()
            .authorizeRequests(auth -> auth
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .build();
    }
}

Q: 如何在 Spring 中使用 JWT 认证?

A: 配置 LCGYL Security:

yaml
lcgyl:
  plugins:
    security:
      enabled: true
      jwt:
        secret: your-secret-key
        expiration: 86400000

然后在控制器中使用:

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);
    }
}

配置

Q: 如何在不同环境使用不同配置?

A: 使用 Spring Profile:

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

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

激活 Profile:

bash
java -jar app.jar --spring.profiles.active=prod

Q: 如何禁用某个插件?

A: 在配置中设置 enabled: false

yaml
lcgyl:
  plugins:
    web:
      enabled: false

测试

Q: 如何测试使用 LCGYL 的 Spring 应用?

A: 使用 @SpringBootTest

java
@SpringBootTest
public class UserServiceTest {
    
    @Autowired
    private UserService userService;
    
    @Test
    public void testCreateUser() {
        User user = new User();
        user.setName("John");
        
        User created = userService.save(user);
        
        assertNotNull(created.getId());
    }
}

Q: 如何 Mock LCGYL 组件?

A: 使用 @MockBean

java
@SpringBootTest
public class OrderServiceTest {
    
    @Autowired
    private OrderService orderService;
    
    @MockBean
    private MessageProducer messageProducer;
    
    @Test
    public void testCreateOrder() {
        Order order = new Order();
        orderService.createOrder(order);
        
        verify(messageProducer).send(eq("order.created"), any());
    }
}

部署

Q: 如何打包 Spring Boot + LCGYL 应用?

A: 使用 Spring Boot Maven/Gradle 插件:

bash
# Maven
mvn clean package

# Gradle
./gradlew build

生成的 JAR 包含所有依赖:

bash
java -jar target/app.jar

Q: 如何配置 Actuator 监控?

A: 添加依赖并配置:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
yaml
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,lcgyl

访问:http://localhost:8080/actuator/health

性能优化

Q: Spring Boot + LCGYL 启动慢怎么办?

A: 几个优化建议:

  1. 禁用不需要的插件
yaml
lcgyl:
  plugins:
    web:
      enabled: false
  1. 使用懒加载
yaml
spring:
  main:
    lazy-initialization: true
  1. 优化组件扫描
java
@SpringBootApplication(scanBasePackages = "com.example.app")
public class Application {
}

Q: 如何优化内存占用?

A: 调整 JVM 参数:

bash
java -Xms256m -Xmx512m -jar app.jar

配置连接池:

yaml
lcgyl:
  plugins:
    data:
      datasource:
        hikari:
          maximum-pool-size: 10
          minimum-idle: 2

迁移

Q: 如何从纯 Spring 项目迁移到 LCGYL?

A: 逐步迁移:

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

Q: 如何从 LCGYL 独立使用迁移到 Spring?

A:

  1. 添加 Spring Boot 依赖
  2. @Component 改为 @Service
  3. @Inject 改为 @Autowired
  4. 使用 Spring 配置文件

更多问题

如果你的问题没有在这里找到答案,可以:

Released under the Apache License 2.0