Spring注解开发
一、组件注册
1.@Configuration和@Bean注解
第一种注册bean的方式:
@Configuration
public class Config {
// 在容器中默认是注册该方法的返回值作为类型,方法名作为bean的id,也可通过@Bean的value来设置id,如@Bean("person01")
@Bean("person01")
public Person person() {
return new Person();
}
}
控制台打印:
config
person01
2.@ComponentScan
只要是标注了@Service、@Controller、@Repository、@Component的注解都是被自动注入进容器中,需要配置包扫描的路径。
@Configuration
@ComponentScan(value = "com.example.demo.hello") // 这是我自己的包路径
// springboot不用配置该注解,也可扫描,原因在于springboot在启动类上的注解包含了@ComponentScan注解,它会扫描跟启动类一个包路径下的所有标了注解的类。需要自己指定路径的时候配置即可。
public class Config {
@Bean
public Person person() {
return new Person();
}
}
持续记录中…