[英]Differences beetwen Beans configuration file and annotation use in Spring MVC?
我正在研究Spring MVC,並且找到了這個簡單的Hello World教程: http ://www.tutorialspoint.com/spring/spring_hello_world_example.htm
在本教程中,作者創建了一個名為Beans.xml的Bean配置文件 ,如下所示:
<?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 Framework可以創建所有定義的bean,並為其分配一個唯一的ID,如tag中所定義。 而且我可以使用標記來傳遞對象創建時使用的不同變量的值。
這是眾所周知的Bean Factory嗎?
我的疑問與以下事情有關:在上一個示例中,我沒有使用Bean配置文件來定義我的bean,而是使用批注定義了什么是Spring bean以及該bean的工作方式(例如,我使用@控制器批注,說Spring(一個類充當控制器Bean)
使用bean配置文件和使用批注具有相同的含義嗎?
我可以同時使用嗎?
例如,如果必須配置JDBC,可以在beans.xml文件中進行配置,同時可以對Controller類使用注解嗎?
特納克斯
是的,你可以做那件事。 在下面找到一個示例,其中控制器已使用批注和sessionFactory編寫控制器,並且已將數據源創建為xml bean,並將其連接到服務中-
<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;
}
希望對您有幫助。 :)
您可以通過xml和注釋使用bean配置。 您甚至可以在xml配置文件中定義您的控制器。
使用@Controller批注允許您使用組件掃描來查找bean。 Controller是一個簡單的原型bean(這就是為什么您可以簡單地將其聲明為xml文件的原因)。
有關@Controller的用法/語義的更多詳細信息,請參見此處
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.