要创建一个不可更改的Bean方法配置属性,可以按照以下步骤进行操作:
public class ImmutableConfig {
private final String property1;
private final int property2;
public ImmutableConfig(String property1, int property2) {
this.property1 = property1;
this.property2 = property2;
}
public String getProperty1() {
return property1;
}
public int getProperty2() {
return property2;
}
}
@Component
public class MyComponent {
private final ImmutableConfig config;
public MyComponent(ImmutableConfig config) {
this.config = config;
}
// 使用配置属性
public void doSomething() {
String property1 = config.getProperty1();
int property2 = config.getProperty2();
// ...
}
}
通过以上步骤,我们创建了一个不可更改的配置属性类,并将其作为Bean注入到目标类中。由于配置属性类的成员变量被声明为final,并且没有提供修改属性值的方法,因此该配置属性类的实例在创建后是不可更改的。
上一篇:不可更改变量v.常量变量
下一篇:不可更改的导航按钮