Eclipse:File → New → Java Project,專案名 HelloSpring
右鍵專案 → Build Path → Configure Build Path → Libraries → Add External JARs:
spring-core、spring-beans、spring-context、spring-expression、spring-aopcommons-loggingspring-asm、spring-aspects、spring-context-support// src/com/example/HelloWorld.java
package com.example;
public class HelloWorld {
private String message;
public void setMessage(String message) { this.message = message; }
public void getMessage() { System.out.println("Your Message: " + message); }
}
// src/com/example/MainApp.java
package com.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// 1. 載入容器,解析 beans.xml
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 2. 從容器獲取 Bean
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
// 3. 使用 Bean
obj.getMessage();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloWorld" class="com.example.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
</beans>
MainApp.java → Run As → Java ApplicationYour Message: Hello World!ClassPathXmlApplicationContext:從類路徑載入 XML 配置FileSystemXmlApplicationContext:從檔案系統載入AnnotationConfigApplicationContext:從註解配置類載入 (現代主流)<bean id="beanId" class="fully.qualified.ClassName"
scope="singleton|prototype"
init-method="initMethodName"
destroy-method="destroyMethodName">
<property name="propertyName" value="value" />
<property name="refProperty" ref="otherBeanId" />
</bean>
getBean("id") 獲取name 對應屬性名,value/ref 對應字面值/Bean 參考singleton (預設,單例)、prototype (每次新建)<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired HelloWorld helloWorld;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) {
helloWorld.getMessage();
}
}
@Component
public class HelloWorld {
@Value("${app.message:Hello Spring Boot!}")
private String message;
public void getMessage() { System.out.println("Your Message: " + message); }
}
app.message=Hello Spring Boot 3!
| 問題 | 原因 | 解決 |
|---|---|---|
| ClassNotFoundException | JAR 未加入 Build Path | 檢查 Libraries、Maven 依賴 |
| FileNotFoundException: beans.xml | 配置檔不在 classpath | 放在 src/ 根目錄或 resources/ |
| NoSuchBeanDefinitionException | Bean id 拼錯或未定義 | 核對 id、package 掃描範圍 |
| BeanCreationException | 建構子/Setter 異常 | 查看堆疊追蹤、檢查依賴注入 |