Spring provides several annotations to declare components as managed beans with in the container.
@Controller: Designates a class as a Spring MVC controller, typically used in conjunction with @RequestMapping.
@Controller
@RequestMapping("user")
public class UserController {
@GetMapping("get/{id}")
public String getUser(@PathVariable String id) {
return "";
}
}
Accessing /user/get/1 invokes getUser() with id set to "1".
@Service: Indicates that a class contains business logic, commonly paired with @Transactional.
@Service
@Transactional
public class UserServiceImpl implements UserService {
public void processOrder(...) {
// ...
}
}
@Repository: Marks a class as a Data Access Object (DAO) responsible for database interactions.
@Repository
public class UserDao implements CrudDao<User, String> {
// ...
}
@RestController: Combines @Controller and @ResponseBody, used for RESTful services that return JSON responses.
@Component: A generic annotation for classes managed by Spring, used when other stereotypes don't fit.
@Configuraton: Declares a class as a source of bean definitions, often used with @Bean.
@Configuration
public class DatabaseConfig {
@Bean(name = "dataSource")
public DataSource dataSource(Environment env) {
HikariDataSource ds = new HikariDataSource();
ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
ds.setUsername(env.getProperty("spring.datasource.username"));
ds.setPassword(env.getProperty("spring.datasource.password"));
return ds;
}
}
The DatabaseConfig class configures a HikariDataSource bean.
@Bean: Applied to methods to indicate that they return a bean managed by the Spring container.
Spring handles bean instantiation and provides lifecycle callbacks:
@PostConstruct: Invokes the annotated method after bean initialization.
@Component
public class DemoComponent {
@PostConstruct
public void initialize() { ... }
}
@PreDestroy: Calls the annotated method before container destruction.
@Service
public class DemoService {
@PreDestroy
public void cleanup() { ... }
}
Beans can be referenced by name or type:
- Name-based: Use
@Qualifierto specify and reference a bean by its name.
@Service
@Qualifier("primaryService")
public class PrimaryService { ... }
@Service
public class ConsumerService {
@Qualifier("primaryService")
private PrimaryService service;
}
- Type-based: Use
@Autowiredto inject by type.
@Service
public class PrimaryService { ... }
@Service
public class ConsumerService {
@Autowired
private PrimaryService service;
}
@Autowired injects dependencies into fields, constructor parameters, or method arguments. For differences between @Autowired, @Resource, and @Inject, consult Spring documentation.