本文目录导读:

在Java中配置Bean参数主要有三种方式:XML配置、注解配置和Java配置类,以下是具体的实现案例。
XML配置方式(传统Spring)
步骤:
- 创建Bean类(包含属性和setter方法)
- 在XML文件中声明Bean并注入参数
示例:
// User.java
public class User {
private String name;
private int age;
// setter方法(必须)
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
@Override
public String toString() {
return "User{name='" + name + "', age=" + age + "}";
}
}
<!-- applicationContext.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">
<!-- 方式1: setter注入 -->
<bean id="user1" class="com.example.User">
<property name="name" value="张三"/>
<property name="age" value="25"/>
</bean>
<!-- 方式2: 构造器注入 -->
<bean id="user2" class="com.example.User">
<constructor-arg name="name" value="李四"/>
<constructor-arg name="age" value="30"/>
</bean>
</beans>
获取Bean:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user1", User.class);
注解配置方式(最常用)
步骤:
- 在Bean类上使用
@Component或其他衍生注解 - 使用
@Value注入单个值,或使用@Autowired注入其他Bean
示例:
// User.java
@Component // 声明为Spring管理的Bean
public class User {
@Value("王五") // 直接注入字符串
private String name;
@Value("28") // 直接注入数字
private int age;
@Value("#{systemProperties['user.region']}") // SpEL表达式
private String region;
// getter...
}
配置类启用组件扫描:
@Configuration
@ComponentScan("com.example")
public class AppConfig {
// 无需额外配置
}
Java配置类方式(推荐用于复杂场景)
步骤:
- 使用
@Configuration标记配置类 - 使用
@Bean注解声明Bean的方法,方法名即Bean名称
示例:
// UserConfig.java
@Configuration
public class UserConfig {
// 方式1: 直接返回实例
@Bean
public User user1() {
return new User("赵六", 22);
}
// 方式2: 从配置文件中读取属性
@Bean
@ConfigurationProperties(prefix = "user.config")
public User user2() {
return new User();
}
// 方式3: 依赖其他Bean
@Bean
public Address address() {
return new Address("北京");
}
@Bean
public User user3(Address address) {
User user = new User("钱七", 35);
user.setAddress(address); // 注入依赖
return user;
}
}
配置文件 (application.properties):
user.config.name=孙八 user.config.age=40
需要启用配置属性绑定:
@SpringBootApplication
@EnableConfigurationProperties // Spring Boot项目中默认启用
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
复杂参数注入案例
注入集合类型:
@Component
public class Team {
@Value("#{'${team.members}'.split(',')}")
private List<String> members;
@Value("#{${team.scores}}") // SpEL解析Map
private Map<String, Integer> scores;
// 或者通过配置类注入
@Bean
public Team team() {
Team team = new Team();
team.setMembers(Arrays.asList("甲", "乙", "丙"));
team.setScores(Map.of("甲", 90, "乙", 85));
return team;
}
}
注入环境变量或系统属性:
@Component
public class DatabaseConfig {
@Value("${db.url:jdbc:mysql://localhost:3306/test}") // 带默认值
private String dbUrl;
@Value("${db.username:root}")
private String username;
@Value("#{systemProperties['java.home']}")
private String javaHome;
}
最佳实践建议
| 场景 | 推荐方式 |
|---|---|
| 简单值注入(字符串、数字) | @Value 注解 |
| 配置属性组(多个相关属性) | @ConfigurationProperties |
| 依赖其他Bean | @Autowired 或构造器注入 |
| 三方库类配置 | Java配置类 @Bean |
| 环境/条件配置 | @Profile + 配置类 |
完整示例(Java配置+属性绑定):
// application.properties
app.user.name=Admin
app.user.age=30
app.user.role=admin
// UserProperties.java
@ConfigurationProperties(prefix = "app.user")
@Component
public class UserProperties {
private String name;
private int age;
private String role;
// getter/setter...
}
// UserService.java
@Service
public class UserService {
private final UserProperties userProps;
public UserService(UserProperties userProps) {
this.userProps = userProps;
}
public void printUser() {
System.out.println(userProps.getName() + " - " + userProps.getRole());
}
}
这种方式将配置外部化,便于维护和不同环境切换。