2017-04-16 62 views
1

必須有這兩個應用程序,實際上這樣做(如果我是正確的)從IOC容器接收對象 - 春

@SpringBootApplication 
public class DemoApplication { 

    @Autowired 
    HelloWorld helloWorld; 

    public static void main(String[] args) { 
     SpringApplication.run(DemoApplication.class, args); 
    } 

    @Bean 
    public CommandLineRunner run() { 
     helloWorld.setMessage("wow"); 
     return (load) -> { 
      helloWorld.getMessage(); 
     }; 
    } 
} 

public class MainApp { 
    public static void main(String[] args) { 
     ApplicationContext context = new 
     ClassPathXmlApplicationContext("Beans.xml"); 
     HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); 
     obj.getMessage(); 
    } 
} 

都使用

@Component 
    public class HelloWorld { 
    private String message; 

    public void setMessage(String message) { 
     this.message = message; 
    } 

    public void getMessage() { 
     System.out.println("Your Message : " + message); 
    } 
} 

helloWord obj唯一的區別是,如果我在我的程序中使用MainApp類,那麼helloWorld類不需要@Component註釋。

我的問題:

如果我是正確的SpringBoot註解使得不需要定義一個ClassPathXmlApplicationContext的。 @Autowire爲我做到了這一點。

我現在感興趣的是,如果我的AutoWire允許在開始時說100個對象,所有這些對象現在在IoC容器中是正確的嗎?

如果是這樣的話:不可能在另一個類的CTOR中分發該容器,並且可以訪問所有保存的對象,如: (HelloWorld)context.getBean(「helloWorld」);或 (someRandomClass)context.getBean( 「someRandomClass」)

public CTOR(IOCContainer container) { 
    this.container = container; 
} 

而不是執行

public CTOR(HelloWorld helloWorld, SomeRandomClass someRandomClass) { 
     this.helloWorld = helloWorld; 
     this.someRandomClass = someRandomClass; 
    } 

如果這是可能的,我該怎麼辦呢? (還有後面的我的問題沒有用例/任務,我感到如果這是可能只是有興趣)

回答

2

,你通過

<bean ... etc. pp. 

定義你的bean及接線配置的XML'ish方式,可以通過使用

@Component 
public class MyClass .... 

或要麼完全取代

@Bean 
public MyClass myClass() {return new MyClass();} 

定義在配置類中。兩種方式都將實體放置在Spring的IoC容器中。

@Autowire只是通知Spring的IoC容器,您希望有一個bean可以滿足注入此地的標記爲@Autowire的實體的合同。

爲了獲得對容器的訪問權限,您只需在需要的地方注入ApplicationContext即可。

+0

感謝您的回答。我該如何注入ApplicationContext?由於我沒有在DemoApplication類中創建ApplicationContext,因此我不知道如何將IoC Cointainer分發到另一個類中。 – PowerFlower

+0

不客氣。 Spring負責設置ApplicationContext。它可以通過使用'@Autowired private ApplicationContext applicationContext''輕鬆注入 – Peter

2

在Spring中創建bean有兩種方法。一個是通過XML配置,另一個是通過註釋配置。註釋配置是首選方法,因爲它比xml配置有很多優勢。

春季開機沒有任何事情與註釋或XML配置。它只是一個簡單的方法來啓動彈簧應用程序。 @Component在應用程序上下文中創建註釋bean的對象。@Import或@ImportResource是用於在Spring引導中從Annotations或XML配置加載配置的註釋。使用Spring引導,你不需要創建ClassPathXMlCOntext或AnnotationContext對象,但是它是由spring引導內部創建的。

@Autowired是一種通過注入而不是緊密耦合代碼將bean引入任何對象的方法。 Spring容器(應用程序上下文)完成注入這項工作。只需自動裝配任何類就不會在Spring上下文中創建對象。它只是指示Spring上下文在這裏設置應用程序上下文中的對象。你需要在xml config /或者@Component @Service其他註解中明確地創建它們。

任何地方都不需要手動出櫃。 U可以只是@Autowire ApplicationContext上下文;在任何其他spring bean對象中。用你可以調用getBean(YourBean.class)來獲取該bean。