2013-01-19 16 views
0

我studyng Spring MVC和我都覺得這個簡單的Hello World教程:http://www.tutorialspoint.com/spring/spring_hello_world_example.htmBeetwen在Spring MVC中使用Bean配置文件和註解的區別?

在本教程中,作者創造一個Bean的配置文件命名beans.xml的,這樣的事情:

<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 

    <bean id="helloWorld" class="com.tutorialspoint.HelloWorld"> 
     <property name="message" value="Hello World!"/> 
    </bean> 

</beans> 

使用tis文件,Spring框架可以創建所有定義的bean,併爲它們分配一個如標籤中定義的唯一ID。我可以使用標籤來傳遞創建對象時使用的不同變量的值。

這是衆所周知的豆廠嗎?

我的疑問與以下事情有關:在我之前的例子中,我沒有使用Bean配置文件來定義我的bean,但我使用註釋來定義什麼是Spring bean以及這個bean如何工作例如我使用@Controller註釋來說Spring表示一個類充當Controller Bean)

使用bean配置文件和使用註釋具有相同的含義嗎?

我可以同時使用嗎?

例如,如果我必須配置JDBC,我可以在beans.xml文件中配置它,同時我可以爲我的Controller類使用註釋嗎?

Tnx

回答

1

的使用/語義信息是的,你可以做到這一點的事情。在下面找到其中控制器已經與註釋和的sessionFactory和數據源寫入一個例子已創建的xml豆被連線到服務 -

<beans ...> 
    <!-- Controller & service base package --> 
    <context:component-scan base-package="com.test.employeemanagement.web" /> 
    <context:component-scan base-package="com.test.employeemanagement.service"/> 

    <bean id="dataSource" 
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
      ... 
    </bean> 
    <bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
    <property name="dataSource" ref="dataSource" /> 
    <property name="annotatedClasses"> 
     <list> 
      <!-- <value>com.vaannila.domain.User</value> --> 
      <value>com.test.employeemanagement.model.Employee</value> 
      ... 
     </list> 
    </property> 
    <property name="hibernateProperties"> 
     <props> 
      <prop key="hibernate.dialect">${hibernate.dialect}</prop> 
      ... 
     </props> 
    </property> 
    </bean> 
    ... 
</beans> 

服務實施例,其中的SessionFactory注入。

@Repository 
public class EmployeeDaoImpl implements EmployeeDao { 

    @Autowired 
    private SessionFactory sessionFactory; 
} 

我希望它可以幫助你。 :)

+0

我想你會說我是很清楚的...... 我只涉及到另一個問題,你說什麼我: 當我創造使用STS \ Eclipse的我不要」一個新的Spring MVC項目沒有這個Beans.xml文件,但我有以下xml配置文件:web.xml和servlet-context.xml(第二個包含組件掃描定義) 我可以將這些bean配置(數據庫連接配置) servlet-context.xml還是我需要一個Beans.xml文件? – AndreaNobili

+0

是的,你可以做到這一點。把所有的數據庫配置到servlet-context中,這將減少維護。 –

0

您可以通過xml和註釋使用bean配置。你甚至可以在xml配置文件中定義你的控制器。

使用@Controller註釋允許您使用組件掃描來查找您的bean。 Controller是一個簡單的構造型bean(這就是爲什麼你可以簡單地聲明它是你的xml文件)。

更多@Controller here

相關問題