spring中获取bean的方式

获取bean的方式

1.可以通过上下文的getBean方法

2.可以通过@Autowired注入

定义controller

@RestController
@RequestMapping("/api")
public class ApiUserController {

    /**
     * 上下文对象实例
     */
    @Autowired
    private  ApplicationContext applicationContext;


    @Autowired
    private IUserService userService;

    @RequestMapping("/getById")
    public RestResponse<User> getUser(Long id) {
        //使用@service注解上的别名进行获取bean
        IUserService service = (IUserService) applicationContext.getBean("IUserService");
        return service.getUserById(id);
    }

    @RequestMapping("/getByIdNoHytrix")
    public RestResponse<User> getUserNoHytrix(Long id) {
        return userService.getUserByIdNoHytrix(id);
    }


}

定义service,注解上的IUserService为自定义的名字,getBean()只能用它

@Service("IUserService")
public class UserService implements IUserService {

    @Autowired
    private UserDao userDao;


    public RestResponse<User> getUserById(Long id) {
        return userDao.getUseById(id);
    }

    public RestResponse<User> getUserByIdNoHytrix(Long id) {
        return userDao.getUseByIdNoHytrix(id);
    }
}

猜你喜欢

转载自www.cnblogs.com/peterpoker/p/9375153.html