本文只列出常用的几个注解,若想知道其他注解请百度spring框架所有注解
@Autowired
@Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。通常我们使用它从容器中获取类对象
@Configuration 和 @Bean
@Configuration注解相当于spring 配置文件中beans标签,而@Bean注解相当于spring配置文件中bean便签,例如:
package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
上面的代码相当于spring配置文件中的以下配置:
<beans>
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" />
</beans>
注意这时我们读取时获取的不再是配置文件而是类,如下所示:
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}