@Bean
概念:
@Bean作用在方法上,一般标明返回的对象直接被Spring管理起来
使用:
调用的时候和@Component一样,用@Autowired 调用有@Bean注解的方法,多用于第三方类无法写@Component的情况
举例:
//想调用的类
public class MessageBuilder {
public void getInstance() {
System.out.println("aaaaaaaaaaa");
}
}
@Configuration
public class TestConfig {
//想交给Spring管理的方法,去调用想调用的类
@Bean
public MessageBuilder messageBuilder(){
return new MessageBuilder();
}
}
public class MallUserController {
//调用
@Autowired
private MessageBuilder messageBuilder;
@PostMapping("/findAllUser")
public Object findAllUser(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize){
messageBuilder.getInstance();
return null;
}
//输出结果:
aaaaaaaaaaa