相同点:
@Component和@Bean的目的是一样的,都是注册bean到Spring容器中。
不同点:
@Component 和 它的子类型(@Controller, @Service and @Repository)注释在类上。告诉Spring,我是一个bean,通过类路径扫描自动检测并注入到Spring容器中。
@Bean不能注释在类上,只能用于在配置类中显式声明单个bean。意思就是,我要获取这个bean的时候,spring要按照这种方式去获取这个bean。默认情况下@Bean注释的方法名作为对象的名字,也可以用name属性定义对象的名字。
所有组件类型及其用途
组件注解 | 用途 |
---|---|
@Component | 标注最普通的组件 |
@Controller | 标注控制层(spring-mvc的注解)(如:*Controller) |
@Service | 标注业务层(如:*Service) |
@Repository | 标注持久层(如:*Dao) |
注:所有组件类型都以相同的方式处理。子类型仅仅是标记,有利于代码可读性而不是特性。
@Controller
@RequestMapping("/web")
public class WebController {
@ResponseBody
@RequestMapping("/msg")
public String message(){
return “msg”;
} }
@Component
@RequestMapping("/web")
public class WebController {
@ResponseBody
@RequestMapping("/msg")
public String message(){
return “msg”;
} }
@Service
@RequestMapping("/web")
public class WebController {
@ResponseBody
@RequestMapping("/msg")
public String message(){
return “msg”;
} }
访问url=locahost:8080/web/msg,三段代码均返回字符串msg。(此web项目我自己用的端口8080)
@Bean的使用
// Just a POJO
public class MessageBuilder {
public String getMsg(){
return "msgBuilder";
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// Let's turn the POJO into a bean
@Configuration
public class AppConfig {
@Bean
public MessageBuilder messageBuilder(){
return new MessageBuilder();
}
}
@Controller
@RequestMapping("/web")
public class WebController {
// Finally, hook it up
@Autowired
private MessageBuilder messageBuilder;
@ResponseBody
@RequestMapping("/msg")
public String message(){
return messageBuilder.getMsg();
}
}