Spring Boot の主要アノテーションと実装例

アプリケーション起動と基本設定

@SpringBootApplication は Spring Boot アプリケーションのエントリーポイントを定義するコンポジットアノテーションです。内部的には @Configuration、@EnableAutoConfiguration、@ComponentScan を統合し、設定の自動化とコンポーネントスキャンを実現します。

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

自動設定機能

@EnableAutoConfiguration は依存関係に基づいて必要な設定を自動適用します。たとえば HSQLDB がクラスパスに存在するとインメモリデータベースが構成されます。

@EnableAutoConfiguration
public class AutoConfigApp {
    public static void main(String[] args) {
        SpringApplication.run(AutoConfigApp.class, args);
    }
}

コンポーネント管理

@Configuration は Java ベースの設定クラスを定義し、@Bean メソッドを通じて Bean を登録します。

@Configuration
public class ServiceConfig {
    @Bean
    public PaymentProcessor paymentProcessor() {
        return new PaymentServiceImpl();
    }
}

@ComponentScan は指定されたパッケージ内のコンポーネントをスキャン対象とします。デフォルトではメインクラスのパッケージが対象です。

@ComponentScan(basePackages = "jp.co.example.service")
public class ComponentConfig {
}

@Service はビジネスロジックを担うサービス層のクラスを明示します。

@Service
public class OrderService {
}

@Repository はデータアクセス層のクラスを定義し、データベース操作を担当します。

@Repository
public class ProductRepository {
}

@Controller は MVC フレームワークの Web コントローラーを定義し、ビューを返却します。

@Controller
public class WebController {
}

@RestController は RESTful API のコントローラーを定義し、戻り値を直接 JSON/XML として返却します。

@RestController
public class ApiResource {
}

Web リクエスト処理

@RequestMapping は HTTP メソッドとパスを処理メソッドにマッピングします。

@Controller
public class HelloController {
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String greet() {
        return "greeting";
    }
}

@GetMapping は GET リクエストを特定のメソッドに束縛します。

@RestController
public class CustomerController {
    @GetMapping("/clients")
    public List<Client> fetchAllClients() {
        return clientService.retrieveAll();
    }
}

@PostMapping は POST リクエストを処理メソッドにマッピングします。

@RestController
public class CustomerController {
    @PostMapping("/clients")
    public Client registerClient(@RequestBody Client newClient) {
        return clientService.create(newClient);
    }
}

@ResponseBody はメソッドの戻り値を HTTP レスポンスボディとして直接返却します。

@RestController
public class GreetingController {
    @GetMapping("/message")
    @ResponseBody
    public String getGreeting() {
        return "Hello from Spring Boot";
    }
}

@RequestBody は HTTP リクエストボディを Java オブジェクトにマッピングします。

@RestController
public class OrderController {
    @PostMapping("/orders")
    public String createOrder(@RequestBody OrderRequest request) {
        orderService.process(request);
        return "Order created";
    }
}

@PathVariable は URI パス中の動的パラメータをメソッド引数にバインドします。

@RestController
public class ProfileController {
    @GetMapping("/profiles/{id}")
    public Client getProfile(@PathVariable Long id) {
        return clientService.findById(id);
    }
}

@RequestParam はクエリパラメータやフォームデータを取得します。

@RestController
public class SearchController {
    @GetMapping("/search")
    public List<Product> findProducts(@RequestParam String keyword) {
        return productService.search(keyword);
    }
}

データアクセス層

@Entity は JPA 永続化クラスを定義し、データベーステーブルと対応付けます。

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long productId;
    private String itemName;
}

@Table はデータベーステーブル名を明示的に指定します。

@Entity
@Table(name = "product_catalog")
public class Product {
    // fields
}

依存性注入と設定

@Value は外部プロパティを Bean に注入します。

@Value("${app.timeout.millis}")
private int connectionTimeout;

@Autowired は依存関係を自動的に解決します。

@Service
public class PaymentService {
    @Autowired
    private PaymentGateway gateway;
}

@Bean は設定クラス内で Bean を定義します。

@Configuration
public class BeanConfig {
    @Bean
    public PaymentGateway paymentGateway() {
        return new StripeGateway();
    }
}

@Conditional は特定の条件が満たされた場合にのみ Bean を生成します。

@Bean
@Conditional(ProductionProfile.class)
public PaymentGateway productionGateway() {
    return new ProductionGateway();
}

@Primary は複数実装がある場合の優先選択を指定します。

@Service
@Primary
public class DefaultPaymentGateway implements PaymentGateway {
}

@Qualifier は特定の Bean 名を指定して注入します。

@Service
public class PaymentService {
    @Autowired
    @Qualifier("stripeGateway")
    private PaymentGateway gateway;
}

@Lazy は Bean の初期化を遅延させます。

@Service
@Lazy
public class BackgroundTaskService {
}

@Scope は Bean のスコープを指定します(シングルトン/プロトタイプなど)。

@Service
@Scope("prototype")
public class SessionScopedService {
}

Lombok を活用したコード簡略化

@Data は@Getter、@Setter、@ToString、@EqualsAndHashCode、@RequiredArgsConstructor を一括で適用します。

import lombok.Data;

@Data
public class Customer {
    private Long customerId;
    private String name;
    private String email;
}

@AllArgsConstructor は全フィールドを引数とするコンストラクタを生成します。

@AllArgsConstructor
public class Product {
    private Long id;
    private String name;
    private double price;
}

@NoArgsConstructor はデフォルトコンストラクタを生成します。

@NoArgsConstructor
public class Order {
    private Long orderId;
    private List<Item> items;
}

タグ: spring-boot jpa lombok restful dependency-injection

5月20日 18:51 投稿