目录
方式一
使用@Autowired注解,会提示不建议使用字段注入,不会影响什么。
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired //不建议使用字段注入
private UserService userService;
}
方式二
使用构造方法,代码会略显繁琐,建议加上final修饰。
import com.demo.service.UserService;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
private final UserService userService; //建议加上final修饰
public UserController(UserService userService) {
this.userService = userService;
}
}
方式三
使用@RequiredArgsConstructor注解,推荐使用,必须加上final修饰。
import com.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class UserController {
private final UserService userService; //必须加上final修饰
}
方式四
使用IOC容器对象,调用getBean()方法,通过Bean的名称获取Bean对象。
注意导包org.springframework.context.ApplicationContext
import com.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class UserController {
private final ApplicationContext applicationContext;
@RequestMapping("/demo")
public void demo() {
UserService userService = (UserService) applicationContext.getBean("userService");
}
}
方式五
使用IOC容器对象,调用getBean()方法,通过Bean的类型获取Bean对象。
import com.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class UserController {
private final ApplicationContext applicationContext;
@RequestMapping("/demo")
public void demo() {
UserService userService = (UserService) applicationContext.getBean(UserService.class);
}
}
方式六
使用IOC容器对象,调用getBean()方法,通过Bean的名称和类型获取Bean对象。
import com.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class UserController {
private final ApplicationContext applicationContext;
@RequestMapping("/demo")
public void demo() {
UserService userService = (UserService) applicationContext.getBean("userService", UserService.class);
}
}