Spring 框架提供了大量的注解来支持各种功能,以下是一些常用的 Spring 注解及其作用:
-
@Component
:- 泛指Spring管理的组件,没有明确的边界。
- 用法:
@Component("myBean")
。
-
@Service
:- 用于标注服务层(业务层)的组件。
- 用法:
@Service("myService")
。
-
@Repository
:- 用于标注数据访问组件,即DAO组件。
- 用法:
@Repository("myRepository")
。
-
@Controller
:- 用于标注控制层的组件,即Spring MVC中的控制器。
- 用法:
@Controller("myController")
。
-
@Configuration
:- 用于定义配置类,可替换xml配置文件。
- 用法:
@Configuration
。
-
@Bean
:- 在配置类中使用,声明一个bean。
- 用法:
@Bean public MyBean myBean() { return new MyBean(); }
。
-
@Value
:- 注入外部配置文件中的值。
- 用法:
@Value("${property}") private String property;
。
-
@Autowired
:- 自动导入依赖的bean。
- 用法:
@Autowired private MyBean myBean;
。
-
@Qualifier
:- 当有多个同一类型的bean时,用于指定具体注入哪一个。
- 用法:
@Autowired @Qualifier("myBean") private MyBean myBean;
。
-
@Scope
:- 定义bean的作用域。
- 用法:
@Scope("prototype")
。
-
@PostConstruct
和@PreDestroy
:- 分别用于在bean创建后和销毁前执行的方法。
- 用法:
@PostConstruct public void init() { ... }
。
-
@Lazy
:- 延迟加载bean,只有在第一次使用该bean时才初始化。
- 用法:
@Lazy @Autowired private MyBean myBean;
。
-
@Profile
:- 指定组件在哪个环境的配置下才能被注册到容器中。
- 用法:
@Profile("dev") @Component public class DevComponent { ... }
。
-
@PropertySource
:- 指定配置文件的位置。
- 用法:
@PropertySource("classpath:app.properties")
。
-
@PropertySources
:- 指定多个配置文件的位置。
- 用法:
@PropertySources({@PropertySource("classpath:app.properties"), @PropertySource("classpath:db.properties")})
。
-
@Import
:- 导入其他配置类。
- 用法:
@Import({Config1.class, Config2.class})
。
-
@Aspect
:- 用于声明一个切面。
- 用法:
@Aspect @Component public class MyAspect { ... }
。
-
@Before
、@After
、@Around
、@Pointcut
:- 用于定义切面的不同通知类型。
- 用法:
@Before("execution(* com.myapp.*.*(..))") public void beforeAdvice() { ... }
。
-
@Transactional
:- 用于声明事务管理。
- 用法:
@Transactional public void myMethod() { ... }
。
-
@EnableTransactionManagement
:- 用于开启基于注解的事务管理。
- 用法:
@Configuration @EnableTransactionManagement public class TransactionConfig { ... }
。
这些注解是 Spring 框架中非常核心和常用的,它们极大地简化了配置和开发过程。