1 2 3 4 5 6 |
@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } |
1 2 3 4 5 6 7 |
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } } |
1 2 3 4 5 |
@SpringBootApplication @ComponentScan({"com.example.main", "com.example.controllers"}) public class MyApplication { // ... } |
1 2 3 4 5 6 7 |
@Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } |
1 2 3 4 5 6 7 8 |
@Service public class UserServiceImpl implements UserService { // 业务逻辑 } @Repository public class UserRepositoryImpl implements UserRepository { // 数据访问逻辑 } |
1 2 3 4 5 6 |
@ConfigurationProperties(prefix = "app") public class AppProperties { private String name; private String version; // getters/setters } |
1 2 3 4 5 |
@Bean @Scope("prototype") public MyPrototypeBean myPrototypeBean() { return new MyPrototypeBean(); } |
1 2 3 4 5 |
@Service public class UserService { @Autowired private UserRepository userRepository; } |
1 2 3 |
@Autowired @Qualifier("primaryDataSource") private DataSource dataSource; |
1 2 3 4 |
3. @Value 作用:注入属性值 使用场景:注入简单配置值 示例: |
1 2 3 4 5 6 7 8 |
@RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public User getUser(@PathVariable Long id) { // ... } } |
1 2 3 4 |
@PostMapping("/create") public ResponseEntity<User> createUser(@RequestBody UserDto userDto) { // ... } |
1 2 3 4 |
@PostMapping public User create(@RequestBody User user) { return userService.save(user); } |
1 2 3 4 |
@GetMapping("/search") public List<User> searchUsers(@RequestParam String keyword) { // ... } |
1 2 3 4 5 6 7 8 |
@Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // ... } |
1 2 3 4 5 6 7 |
@Service public class UserService { @Transactional public void updateUser(User user) { // ... } } |
作用:将JPA仓库暴露为REST端点
使用场景:快速开发RESTful数据服务
示例:
1 2 3 |
@RepositoryRestResource(path = "users") public interface UserRepository extends JpaRepository<User, Long> { } |
1 2 3 4 5 6 |
@SpringBootTest class MyIntegrationTests { @Autowired private MyService myService; // 测试方法 } |
1 2 3 4 5 6 |
@WebMvcTest(UserController.class) class UserControllerTests { @Autowired private MockMvc mockMvc; // 测试方法 } |
1 2 3 4 5 6 7 |
@Service public class UserService { @Cacheable("users") public User getUser(Long id) { // 只有第一次会执行,后续从缓存获取 } } |
1 2 3 4 5 6 7 |
@Component public class MyScheduler { @Scheduled(fixedRate = 5000) public void doTask() { // 每5秒执行一次 } } |
1 2 3 4 5 6 7 |
@Service public class AsyncService { @Async public void asyncMethod() { // 异步执行 } } |