0

我正在学习 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 框架可以创建所有定义的 bean,并为它们分配一个唯一的 ID,如 tag 中定义的那样。我可以使用标签来传递对象创建时使用的不同变量的值。

这是众所周知的豆厂吗?

我的疑问与以下事情有关:在我之前的示例中,我没有使用 Bean 配置文件来定义我的 bean,但我使用注解来定义什么是 Spring bean 以及这个 bean 是如何工作的(例如我使用@控制器注释说 Spring 一个类充当控制器 Bean)

使用bean配置文件和使用注解的意思一样吗?

我可以同时使用吗?

例如,如果我必须配置 JDBC,我可以在 beans.xml 文件中配置它,同时我可以为我的 Controller 类使用注释吗?

肿瘤坏死因子

4

2 回答 2

1

是的,你可以做那件事。在下面找到一个示例,其中控制器使用注释和 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;
}

我希望它对你有帮助。:)

于 2013-01-19T12:12:57.723 回答
0

您可以通过 xml 和注释来使用 bean 配置。您甚至可以在 xml 配置文件中定义您的控制器。

使用@Controller 注解允许您使用组件扫描来查找您的 bean。控制器是一个简单的原型 bean(这就是为什么您可以简单地将其声明为您的 xml 文件)。

有关@Controller 用法/语义的更多详细信息,请点击此处

于 2013-01-19T12:09:51.770 回答