봄에는 자동 배선이 어떻게 작동합니까?
제어의 반전이 어떻게 되어 있는지 조금 혼란스럽습니다.IoC에서 동작합니다.Spring.
, 제가 라고 합니다.UserServiceImplUserService인터페이스입니다.
 어때요?@Autowired
그리고 내 안에Controllers 하면 instantiate한 사람instance이서서 의상? ??? 상??
제가 그냥 다음과 같이 하면 될까요?
UserService userService = new UserServiceImpl();
첫째, 그리고 가장 중요한 것은 모든 스프링 콩이 관리되고 있으며, "애플리케이션 컨텍스트"라고 불리는 컨테이너 안에서 "살아있다"는 것입니다.
둘째, 각 응용 프로그램에는 해당 컨텍스트에 대한 진입점이 있습니다.웹 어플리케이션에는 Servlet이 있고 JSF는 el-resolver 등을 사용합니다.또, 애플리케이션 콘텍스트가 부트 스트랩 되어 있고, 모든 콩이 자동 접속되어 있는 곳도 있습니다.웹 어플리케이션에서는 스타트업 리스너로 사용할 수 있습니다.
자동 배선은 한 개의 콩 인스턴스를 다른 콩 인스턴스의 원하는 필드에 배치함으로써 이루어집니다.두 클래스는 모두 빈 클래스여야 합니다. 즉, 애플리케이션 컨텍스트에 존재하도록 정의해야 합니다.
애플리케이션 컨텍스트에서 '생존'이란 무엇입니까?즉, 컨텍스트는 사용자가 아니라 개체를 인스턴스화합니다.다시 말해, 넌 절대로new UserServiceImpl() 는 각  - 컨테이너는 각 주입 지점을 찾습니다.
컨트롤러에는 다음 기능만 있습니다.
@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {
    // Tells the application context to inject an instance of UserService here
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {
        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);
    }
}
몇 가지 주의:
- 고객님의 고객명applicationContext.xml기능을 .<context:component-scan>「스캔」이 되도록 합니다.@Controller,@Service석석등 。
- Spring-MVC 어플리케이션의 엔트리 포인트는 Dispatcher Servlet이지만 이 엔트리 포인트는 숨겨져 있기 때문에 어플리케이션콘텍스트의 직접적인 상호작용과 부트스트래핑이 백그라운드에서 이루어집니다.
- UserServiceImpl- 콩을 쓰거나 둘 중를 쓰거나- <bean id=".." class="..">'사용할 수 없습니다'를 합니다.- @Service주석입니다.그것이 유일한 실장이기 때문이다.- UserService주사하다.
- ★★★★★★★★★★★★★★★★★★★외@Autowired주석, 스프링은 XML 구성 가능한 자동 배선을 사용할 수 있습니다.이 경우 기존 콩과 일치하는 이름 또는 유형을 가진 모든 필드에 콩이 자동으로 주입됩니다.사실, 이것은 자동 배선의 초기 개념이었습니다. 즉, 아무런 구성 없이 종속성이 있는 필드를 주입하는 것입니다.:@Inject,@Resource사용할 수도 있습니다.
주석 경로를 지정할지 아니면 빈 XML 정의 경로를 지정할지 여부에 따라 달라집니다.
, 당신의 를 defined your, defined your your your your your your 에 정의된  합시다.applicationContext.xml:
<beans ...>
    <bean id="userService" class="com.foo.UserServiceImpl"/>
    <bean id="fooController" class="com.foo.FooController"/>
</beans>
애플리케이션 기동시에 자동 배선이 발생합니다.★★★★★★★★★★★★★★★★.fooController는 사케, 사케, 사케, 사케, 사케, 사케를 합니다.UserServiceImpl을 사용하다
public class FooController {
    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;
    // rest of class goes here
}
 @Autowired은 봄의 applicationContext이 됩니다 자동주입이 됩니다. 의 " " " 가  경우UserService콩은 어떤 것을 사용해야 하는지 판단해야 합니다.
다음을 수행할 경우:
UserService service = new UserServiceImpl();
는 수신되지 않습니다.@Autowired★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
@Autowired봄 2.5일 
예를 들어 다음과 같습니다.
class A {
    private int id;
    // With setter and getter method
}
class B {
    private String name;
    @Autowired // Here we are injecting instance of Class A into class B so that you can use 'a' for accessing A's instance variables and methods.
    A a;
    // With setter and getter method
    public void showDetail() {
        System.out.println("Value of id form A class" + a.getId(););
    }
}
는 어떻게 ?@Autowired내에고고고고고고고?
예:
class EnglishGreeting {
   private Greeting greeting;
   //setter and getter
}
class Greeting {
   private String message;
   //setter and getter
}
은 .xml 파일을 사용하지 .@Autowired:
<bean id="englishGreeting" class="com.bean.EnglishGreeting">
   <property name="greeting" ref="greeting"/>
</bean>
<bean id="greeting" class="com.bean.Greeting">
   <property name="message" value="Hello World"/>
</bean>
「 」를 사용하고 @Autowired 다음아까,아까다,아까다.
class EnglishGreeting {
   @Autowired //so automatically based on the name it will identify the bean and inject.
   private Greeting greeting;
   //setter and getter
}
은 .xml 파일을 사용하지 .@Autowired:
<bean id="englishGreeting" class="com.bean.EnglishGreeting"></bean>
<bean id="greeting" class="com.bean.Greeting">
   <property name="message" value="Hello World"/>
</bean>
아직 의문이 남는 경우는, 아래의 라이브 데모를 참조해 주세요.
을 달기만 .UserServiceImpl석석: :
@Service("userService")
스프링 컨테이너는 서비스 등록 시 이 클래스의 라이프 사이클을 관리합니다.
다음으로 컨트롤러에서 자동 배선(인스턴스)하여 기능을 사용할 수 있습니다.
@Autowired
UserService userService;
스프링 의존성 주입은 클래스에서 커플링을 제거하는 데 도움이 됩니다.다음과 같은 개체를 만드는 대신:
UserService userService = new UserServiceImpl();
DI를 소개한 후 사용합니다.
@Autowired
private UserService userService;
에 대한 을 만들어야 .ServiceConfiguration 그 후 파일을 . 수입하다ServiceConfiguration의 신 to to 에 대한 클래스WebApplicationConfiguration컨트롤러에 다음과 같이 빈을 자동 배선할 수 있도록 합니다.
public class AccController {
    @Autowired
    private UserService userService;
} 
Java Configuration 기반의 POC의 예를 다음에 나타냅니다.
를 들어서 예를 들면 세 요.@Autowired.
1. @Autowired[ Properties ]()에서
주석은 속성에서 직접 사용할 수 있으므로 getter 및 setter가 필요하지 않습니다.
    @Component("userService")
    public class UserService {
        public String getName() {
            return "service name";
        }
    }
    @Component
    public class UserController {
        @Autowired
        UserService userService
    }
예에서는 은 봄을 합니다.userService 때UserController성됩니니다다
2. @Autowired
@Autowired을 사용법예제에서는 메서드에  메서드를 합니다.userService 때UserController성됩니니다다
public class UserController {
    private UserService userService;
    @Autowired
    public void setUserService(UserService userService) {
            this.userService = userService;
    }
}
3. @Autowired Constructors
@Autowired주석도 생성자에 사용할 수 있습니다.예제에서는 의 과 같습니다.userService됩니다.UserController성됩니니다다
public class UserController {
    private UserService userService;
    @Autowired
    public UserController(UserService userService) {
        this.userService= userService;
    }
}
간단히 말하면, 자동 배선, 자동 배선 링크입니다.이제 누가 어떤 종류의 배선을 하고 있는지에 대한 질문이 나옵니다.답변: 컨테이너가 이를 수행하고 보조 유형의 배선이 지원됩니다. 원형은 수동으로 수행해야 합니다.
질문:.컨테이너는 어떤 유형의 배선을 알 수 있습니까?
답변: byType, byName, constructor로 정의합니다.
질문:.자동 배선 유형을 정의하지 않는 방법이 있습니까?
답변: 네, @Autowired라는 하나의 주석을 사용하여 확인할 수 있습니다.
질문:.하지만 시스템이 어떻게 알 수 있을까요? 이런 유형의 보조 데이터를 선택해야 합니까?
답변: 이 데이터는 spring.xml 파일 또는 스테로타입 주석을 사용하여 클래스에 제공하므로 컨테이너가 직접 개체를 만들 수 있습니다.
표준 방법:
@RestController
public class Main {
    UserService userService;
    public Main(){
        userService = new UserServiceImpl();
    }
    @GetMapping("/")
    public String index(){
        return userService.print("Example test");
    }
}
사용자 서비스 인터페이스:
public interface UserService {
    String print(String text);
}
UserServiceImpl 클래스:
public class UserServiceImpl implements UserService {
    @Override
    public String print(String text) {
        return text + " UserServiceImpl";
    }
}
 ★★★★★Example test UserServiceImpl
이는 긴밀하게 결합된 클래스의 좋은 예이며 설계 불량이며 테스트에 문제가 있습니다(Power Mockito도 불량).
이제 Spring Boot 의존성 주입을 살펴보겠습니다. 느슨한 커플링의 좋은 예입니다.
인터페이스는 그대로입니다.
메인 클래스:
@RestController
public class Main {
    UserService userService;
    @Autowired
    public Main(UserService userService){
        this.userService = userService;
    }
    @GetMapping("/")
    public String index(){
        return userService.print("Example test");
    }
}
Service User Impl 클래스:
@Component
public class UserServiceImpl implements UserService {
    @Override
    public String print(String text) {
        return text + " UserServiceImpl";
    }
}
 ★★★★★Example test UserServiceImpl
이제 테스트를 쉽게 작성할 수 있습니다.
@RunWith(MockitoJUnitRunner.class)
public class MainTest {
    @Mock
    UserService userService;
    @Test
    public void indexTest() {
        when(userService.print("Example test")).thenReturn("Example test UserServiceImpl");
        String result = new Main(userService).index();
        assertEquals(result, "Example test UserServiceImpl");
    }
}
.@Autowired주석은 생성자에 표시되지만 세터 또는 필드에서도 사용할 수 있습니다.
컨트롤의 반전 개념 전체를 통해 수동으로 개체를 인스턴스화하고 필요한 모든 종속성을 제공해야 하는 번거로움에서 자유로워집니다.을 달 때 "예: " " " " " " )@Service은 자동으로  스프링은 자동으로 객체를 인스턴스화합니다.주석을 잘 모르는 경우 XML 파일을 대신 사용할 수도 있습니다.수업 .newcontext  않은 를 사용합니다.
「 」는, 「 」를하게 할  것에 해 주세요.@Autowired <context:annotation-config/>스프링 컨피규레이션파일에 격납합니다. 하면 " " " 가 됩니다.AutowiredAnnotationBeanPostProcessor주석 처리를 처리합니다.
그런 다음 필드 주입 방식을 사용하여 서비스를 자동 연결할 수 있습니다.
public class YourController{
 @Autowired
 private UserService userService; 
}
나는 이것을 Spring @autowired 주석에서 찾았다.
언급URL : https://stackoverflow.com/questions/3153546/how-does-autowiring-work-in-spring
'programing' 카테고리의 다른 글
| 개인 메서드를 호출할 방법이 있나요? (0) | 2022.07.31 | 
|---|---|
| 응용 프로그램을 배포할 때 "무제한 강도" JCE 정책 파일이 설치되지 않도록 하려면 어떻게 해야 합니까? (0) | 2022.07.31 | 
| C에서 2개의 스트링을 연결하려면 어떻게 해야 하나요? (0) | 2022.07.30 | 
| Cypress에서 Vuex getter에 액세스하는 올바른 방법은 무엇입니까? (0) | 2022.07.30 | 
| v-for 값을 v-if에 바인딩하는 방법 (0) | 2022.07.30 |