创建1、CPU类,包括显示CPU的详细信息方法;2、电脑类,包括查看CPU信息方法,该方法依赖CPU类的显示CPU信息方法;3、在Spring中用Maven配置两个类的依赖注入关系 ;4、应用类用main方法调用电脑类的查看CPU信息方法
时间: 2024-09-24 21:02:37 浏览: 48
创建一个简单的Java示例来展示这个场景:
首先,我们定义一个`CPU`类,它有一个显示详细信息的方法:
```java
public class CPU {
private String brand;
private int cores;
// 构造函数
public CPU(String brand, int cores) {
this.brand = brand;
this.cores = cores;
}
// 显示CPU详细信息的方法
public void displayInfo() {
System.out.println("CPU品牌:" + brand);
System.out.println("核心数:" + cores);
}
}
```
接着,我们创建一个`Computer`类,它有一个依赖于`CPU`类的`viewCPUInfo`方法:
```java
import org.springframework.beans.factory.annotation.Autowired;
public class Computer {
private CPU cpu;
@Autowired
public Computer(CPU cpu) {
this.cpu = cpu;
}
// 观察并调用CPU的显示信息方法
public void viewCPUInfo() {
cpu.displayInfo();
}
}
```
在Spring框架中,我们需要添加Maven依赖,并在配置文件(如applicationContext.xml 或 application.yml)中设置bean的依赖关系,这里假设我们使用XML配置:
```xml
<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.xsd">
<bean id="cpu" class="com.example.CPU">
<constructor-arg value="Intel" />
<constructor-arg value="4" />
</bean>
<bean id="computer" class="com.example.Computer">
<constructor-arg ref="cpu" />
</bean>
</beans>
```
最后,在`Application`类中,我们可以通过Spring IoC容器启动程序并调用`Computer`类的方法:
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class, args);
Computer computer = context.getBean(Computer.class);
computer.viewCPUInfo(); // 这里会自动使用CPU bean提供的信息
}
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)