2015-08-17 35 views
1

一類在Spring中,註釋和xml必須一起使用嗎?

public class A { 

    private String name; 

    public A() { 
    } 

    public String getName() { 
     return this.name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

} 

的BeanFactory類

public class BeanFactory implements InitializingBean, DisposableBean{ 

    private A a; 

    public BeanFactory(){ 

    } 

    public BeanFactory(A a){ 
     this.a = a; 
    } 

    public void printAName(){ 
     System.out.println("Class BeanFactory: beanFactory.printAName -> a.getName() = " + a.getName()); 

    }  

} 

public class Main { 
    public static void main(String[] args) { 
     AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
       "ApplicationContext.xml"); 

     BeanFactory beanFactory = applicationContext.getBean("beanFactory", 
       BeanFactory.class); 

     beanFactory.printAName(); 
    } 
} 

的ApplicationContext

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <context:annotation-config /> 

    <bean id="beanFactory" class="testSpring.BeanFactory"> 
     <constructor-arg ref="a1"/> 
    </bean> 

    <bean id="a1" class="testSpring.A"> 
     <property name="name" value="I am A!"></property> 
    </bean> 

</beans> 

運行的結果:Class BeanFactory: beanFactory.printAName -> a.getName() = I am A!

就像你所看到的,在這裏我不使用任何註釋。但代碼工作得益於xml文件。

  1. 所以xml不需要註釋..?我可以使用其中一種嗎?

  2. 如果我在此應用程序中使用註釋(例如@Autowired)而不是bean xml,那麼有可能嗎?你能告訴我如何?

  3. 或者註釋必須要求xml引用?

所以..註釋和XML必須一起使用?由於

+2

號您可以使用註釋,XML或二者兼有。 – Kayaman

+0

好的,如果我只想使用註釋,我該怎麼辦? – Dave

+2

我建議大家學習文檔以及谷歌搜索。在這裏得到一個正確答案的問題太廣泛了(這也取決於你在做什麼和使用什麼)。在討論基於Spring的註釋配置時,經常使用術語「java config」。 – Kayaman

回答

0

您應該使用註釋配置,這是觀念

@Component 
class Bean1 { 
    public Bean1() { 
     System.out.println(getClass()); 
    } 
} 


@Configuration 
@ComponentScan("test") 
public class Config { 

    public static void main(String[] args) { 
     ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); 
    } 
} 

詳見春天文檔

相關問題