
前言
在Spring MVC的时候,我们使用xml来配置bean,如今的Spring boot推荐我们使用元注解的发生,那就听Spring Boot的推荐,下面我就为大家来介绍下Spring Boot Bean的使用。
声明为SpringBean的元注解
@Repository注解:Dao层使用
@Service注解:Service层使用
@Controller注解:Controller层使用
@Component注解:这个注解和上面注解功能差不多,上面三个注解都确定了使用了场景,这个注解没有确定使用的场景。
Spring Boot还为我们提供了一种声明bean的方法
在类上标注为配置类@Configuration
@SpringBootApplication中有继承下来的@Configuration注解,所以不需要重复标注
@SpringBootApplication
public class DomeApplication {
public static void main(String[] args) {
SpringApplication.run(DomeApplication.class, args);
}
@Bean
public User user(){
User user = new User();
user.setId(1L);
user.setName("GoslingWu");
return user;
}
}
使用注解声明bean时可以默认值
@Component
public class UserComponent {
@Value("1")
private Long id;
@Value("GoslingWu")
private String name;
}