第一步,任意创建一个类
public class User{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第二步,在配置类或者其他类创建@bean方法
@Configuration
public class TokenConfig {
@Bean// (name = "myUser")
public User myUser() {
User u = new User("da");
return u;
}
}
第三步,使用
@Controller
public class LoginController {
// 这里需要使用依赖注入,否则报错
@Autowired
private User u;
@RequestMapping("/login")
public String login(){
System.out.println(u.getName());
return "登录成功";
}
}
QS:如果未使用@Bean创建对象,仍使用依赖注入,那么启动服务时将会报错
Description:
Field u in com.josion.cas.controller.LoginController required a bean of type 'com.josion.cas.pojo.User' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.josion.cas.pojo.User' in your configuration.