Spring对象需要使用new 创建
时间: 2023-11-27 08:50:13 浏览: 47
在 Spring 中,我们通常不直接使用 `new` 关键字来创建对象,而是使用 Spring 容器来管理对象的生命周期。Spring 容器会负责创建、初始化、配置和管理对象,我们只需要在配置文件中声明需要管理的对象,然后通过容器来获取这些对象。
在配置文件中,我们可以使用 `bean` 标签来声明一个 Bean 对象,例如:
```xml
<bean id="userService" class="com.example.UserService">
<property name="userDao" ref="userDao" />
</bean>
<bean id="userDao" class="com.example.UserDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
```
在上面的配置文件中,我们声明了一个名为 `userService` 的 Bean 对象,它的类是 `com.example.UserService`,并且它依赖于一个名为 `userDao` 的 Bean 对象和一个名为 `dataSource` 的 Bean 对象。当我们需要使用 `userService` 对象时,只需要从 Spring 容器中获取即可:
```java
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
```
这样,我们就可以通过 Spring 容器来管理对象,而不需要使用 `new` 关键字来创建对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)