refactor: 将 apps 重命名为 containers 并同步 harness 默认路径

example-project 与占位符/安装器默认改为 containers/backend|frontend,探测仍兼容旧 apps/。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ning-inspire
2026-11-17 13:46:59 +08:00
parent 26ebadc3ca
commit 28f0490dbf
74 changed files with 102 additions and 79 deletions

View File

@@ -0,0 +1,11 @@
package com.consultation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsultationApplication {
public static void main(String[] args) {
SpringApplication.run(ConsultationApplication.class, args);
}
}

View File

@@ -0,0 +1,17 @@
package com.consultation.adapter.rest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/health")
public class HealthController {
@GetMapping
public Map<String, String> health() {
return Map.of("status", "UP");
}
}

View File

@@ -0,0 +1,25 @@
package com.consultation.domain.businessrule;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 业务规则配置空壳。后续按 feature 扩展字段,并由 YAML 绑定。
*/
@Data
@Component
@ConfigurationProperties(prefix = "business-rules")
public class BusinessRuleConfig {
private Map<String, Object> rules = new HashMap<>();
private List<String> publicEndpoints = new ArrayList<>(List.of(
"/api/v1/health"
));
}

View File

@@ -0,0 +1,6 @@
package com.consultation.domain.businessrule;
public interface IBusinessRule {
String getRuleName();
String getDescription();
}

View File

@@ -0,0 +1,18 @@
package com.consultation.domain.datadictionary;
import lombok.Builder;
import lombok.Value;
import java.util.List;
@Value @Builder
public class DataDictionary {
String typeName;
String description;
List<Item> items;
@Value @Builder
public static class Item {
String code;
String description;
}
}

View File

@@ -0,0 +1,6 @@
package com.consultation.domain.datadictionary;
public interface DataDictionaryType {
Class<? extends Description> getClazz();
String getDescription();
}

View File

@@ -0,0 +1,20 @@
package com.consultation.domain.datadictionary;
import java.util.Arrays;
import java.util.List;
public final class DataDictionaryUtil {
private DataDictionaryUtil() {}
public static DataDictionary toDataDictionary(DataDictionaryType type) {
var items = Arrays.stream(type.getClazz().getEnumConstants())
.map(e -> DataDictionary.Item.builder().code(e.getCode()).description(e.getDescription()).build())
.toList();
return DataDictionary.builder().typeName(((Enum<?>) type).name()).description(type.getDescription()).items(items).build();
}
public static List<DataDictionary> allDictionaries(DataDictionaryType[] types) {
return Arrays.stream(types).map(DataDictionaryUtil::toDataDictionary).toList();
}
}

View File

@@ -0,0 +1,10 @@
package com.consultation.domain.datadictionary;
import java.util.Collections;
import java.util.Map;
public interface Description {
String getCode();
String getDescription();
default Map<String, String> getExtraFields() { return Collections.emptyMap(); }
}

View File

@@ -0,0 +1,6 @@
package com.consultation.domain.service;
public interface PasswordService {
String encode(String raw);
boolean matches(String raw, String encoded);
}

View File

@@ -0,0 +1,47 @@
package com.consultation.infrastructure.config;
import com.consultation.domain.businessrule.BusinessRuleConfig;
import com.consultation.domain.businessrule.IBusinessRule;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Component
@RequiredArgsConstructor
public class BusinessRuleProvider {
private final BusinessRuleConfig config;
private final List<IBusinessRule> ruleDefinitions;
private final ObjectMapper objectMapper;
private final Map<String, Map<String, Object>> ruleCache = new LinkedHashMap<>();
@PostConstruct
public void init() {
Map<String, Object> projected = projectConfig();
for (IBusinessRule rule : ruleDefinitions) {
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("ruleName", rule.getRuleName());
detail.put("description", rule.getDescription());
if (!projected.isEmpty()) {
detail.put("config", projected);
}
ruleCache.put(rule.getRuleName(), detail);
}
}
public List<Map<String, Object>> getAllRules() {
return new ArrayList<>(ruleCache.values());
}
private Map<String, Object> projectConfig() {
return objectMapper.convertValue(config, new TypeReference<Map<String, Object>>() {
});
}
}

View File

@@ -0,0 +1,11 @@
package com.consultation.infrastructure.config;
import org.springframework.context.annotation.Configuration;
/**
* 业务规则 Bean 注册入口(当前为空壳)。
* iteration1 实现时在此注册 {@link com.consultation.domain.businessrule.IBusinessRule} 实现。
*/
@Configuration
public class BusinessRuleRegistration {
}

View File

@@ -0,0 +1,41 @@
package com.consultation.infrastructure.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ErrorResponse> handleBadArg(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(new ErrorResponse("PARAM_ERROR", e.getMessage()));
}
@ExceptionHandler(IllegalStateException.class)
public ResponseEntity<ErrorResponse> handleConflict(IllegalStateException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(new ErrorResponse("BUSINESS_CONFLICT", e.getMessage()));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException e) {
var msg = e.getBindingResult().getFieldError();
return ResponseEntity.badRequest().body(new ErrorResponse("VALIDATION_ERROR", msg != null ? msg.getDefaultMessage() : "参数错误"));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleOther(Exception e) {
log.error("Unexpected error", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ErrorResponse("SYSTEM_ERROR", "系统繁忙"));
}
public record ErrorResponse(String errorCode, String errorMessage, Object data) {
public ErrorResponse(String errorCode, String errorMessage) {
this(errorCode, errorMessage, null);
}
}
}

View File

@@ -0,0 +1,18 @@
package com.consultation.infrastructure.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper m = new ObjectMapper();
m.registerModule(new JavaTimeModule());
m.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return m;
}
}

View File

@@ -0,0 +1,17 @@
package com.consultation.infrastructure.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor interceptor() {
MybatisPlusInterceptor i = new MybatisPlusInterceptor();
i.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return i;
}
}

View File

@@ -0,0 +1,33 @@
package com.consultation.infrastructure.config;
import com.consultation.infrastructure.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtFilter;
@Bean
public SecurityFilterChain chain(HttpSecurity http) throws Exception {
http.csrf(c -> c.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(a -> a
.requestMatchers("/api/v1/health").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}

View File

@@ -0,0 +1,17 @@
package com.consultation.infrastructure.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
}

View File

@@ -0,0 +1,49 @@
package com.consultation.infrastructure.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Collections;
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider tokenProvider;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String bearer = request.getHeader("Authorization");
if (StringUtils.hasText(bearer) && bearer.startsWith("Bearer ")) {
String token = bearer.substring(7);
if (tokenProvider.validate(token)) {
var claims = tokenProvider.parse(token);
String role = claims.get("role", String.class);
UserContextHolder.set(UserContext.builder()
.userId(claims.getSubject())
.email(claims.get("email", String.class))
.role(role)
.build());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
claims.getSubject(), null,
role != null ? Collections.singletonList(new SimpleGrantedAuthority(role))
: Collections.emptyList()
)
);
}
}
try { chain.doFilter(request, response); } finally { UserContextHolder.clear(); SecurityContextHolder.clearContext(); }
}
}

View File

@@ -0,0 +1,36 @@
package com.consultation.infrastructure.security;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
@Component
public class JwtTokenProvider {
private final SecretKey key;
private final long expiration;
public JwtTokenProvider(@Value("${jwt.secret}") String secret, @Value("${jwt.expiration}") long exp) {
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
this.expiration = exp;
}
public String generate(String userId, String email, String role) {
Date now = new Date();
return Jwts.builder().subject(userId).claim("email", email).claim("role", role)
.issuedAt(now).expiration(new Date(now.getTime() + expiration)).signWith(key).compact();
}
public io.jsonwebtoken.Claims parse(String token) {
return Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload();
}
public boolean validate(String token) {
try { parse(token); return true; } catch (Exception e) { return false; }
}
}

View File

@@ -0,0 +1,16 @@
package com.consultation.infrastructure.security;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class PasswordServiceImpl implements com.consultation.domain.service.PasswordService {
private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
@Override
public String encode(String raw) { return encoder.encode(raw); }
@Override
public boolean matches(String raw, String encoded) { return encoder.matches(raw, encoded); }
}

View File

@@ -0,0 +1,14 @@
package com.consultation.infrastructure.security;
public class SecurityUtils {
public static UserContext currentUser() {
UserContext c = UserContextHolder.get();
if (c == null) throw new IllegalStateException("未登录");
return c;
}
public static String currentUserId() { return currentUser().getUserId(); }
public static boolean isAdmin() {
UserContext c = UserContextHolder.get();
return c != null && "ROLE_ADMIN".equals(c.getRole());
}
}

View File

@@ -0,0 +1,12 @@
package com.consultation.infrastructure.security;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data @Builder @AllArgsConstructor
public class UserContext {
private String userId;
private String email;
private String role;
}

View File

@@ -0,0 +1,8 @@
package com.consultation.infrastructure.security;
public class UserContextHolder {
private static final ThreadLocal<UserContext> CTX = new ThreadLocal<>();
public static void set(UserContext c) { CTX.set(c); }
public static UserContext get() { return CTX.get(); }
public static void clear() { CTX.remove(); }
}

View File

@@ -0,0 +1,29 @@
server:
port: 8080
spring:
application:
name: consultation-backend
datasource:
url: jdbc:mysql://localhost:3306/consultation?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: <your-mysql-password>
driver-class-name: com.mysql.cj.jdbc.Driver
flyway:
enabled: true
locations: classpath:db/migration
baseline-on-migrate: true
mybatis-plus:
mapper-locations: classpath:mapper/**/*.xml
type-aliases-package: com.consultation.infrastructure.persistence.po
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: INPUT
jwt:
secret: <your-jwt-secret>
expiration: 86400000
business-rules:
public-endpoints:
- /api/v1/health

View File

@@ -0,0 +1,25 @@
package com.consultation;
import com.consultation.config.ResetDbService;
import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class TestBase {
@LocalServerPort
int port;
@Autowired
ResetDbService resetDbService;
@BeforeEach
void setUp() {
RestAssured.port = port;
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
resetDbService.resetAll();
}
}

View File

@@ -0,0 +1,14 @@
package com.consultation.adapter.rest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class HealthControllerTest {
@Test
void should_return_up_when_get_health() {
var body = new HealthController().health();
assertEquals("UP", body.get("status"));
}
}

View File

@@ -0,0 +1,42 @@
package com.consultation.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.util.List;
@Component
public class ResetDbService {
private final JdbcTemplate jdbc;
private final DataSource dataSource;
@Value("classpath:data.sql")
private Resource dataScript;
public ResetDbService(JdbcTemplate jdbc, DataSource dataSource) {
this.jdbc = jdbc;
this.dataSource = dataSource;
}
public void resetAll() {
List<String> tables = jdbc.queryForList(
"SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_schema=DATABASE()",
String.class
);
jdbc.execute("SET FOREIGN_KEY_CHECKS = 0");
for (String table : tables) {
jdbc.execute("TRUNCATE TABLE " + table);
}
jdbc.execute("SET FOREIGN_KEY_CHECKS = 1");
reSeed();
}
private void reSeed() {
ResourceDatabasePopulator populator = new ResourceDatabasePopulator(dataScript);
populator.execute(dataSource);
}
}

View File

@@ -0,0 +1,19 @@
spring:
datasource:
url: jdbc:mysql://localhost:3306/consultation_test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
sql:
init:
mode: always
schema-locations: classpath:schema.sql
data-locations: classpath:data.sql
flyway:
enabled: false
jwt:
secret: test-secret-key-for-mysql-tests-only
expiration: 86400000
business-rules:
public-endpoints:
- /api/v1/health

View File

@@ -0,0 +1 @@
-- Skeleton: no seed data.

View File

@@ -0,0 +1 @@
-- Skeleton: no business tables. Recreate via Flyway when implementing iteration1 features.