一、配置对象类
package com.godgy.constructor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author : Mr.Godgy
* @version : 1.0
* @date : 2022/11/4
* @description:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ConfigBean {
private String name;
private String server;
private String host;
private String language;
}
二、配置类
package com.godgy.constructor;
/**
* @author : Mr.Godgy
* @version : 1.0
* @date : 2022/11/4
* @description:
*/
public class Configure {
private ConfigBean config = new ConfigBean();
public Configure() {
config.setServer("localhost");
config.setHost("8080");
config.setName("Tomcat");
config.setLanguage("zh_CN");
}
public Configure(ConfigBean config) {
this.config = config;
}
public String getConfig (){
return config.toString();
}
}
这里巧妙运用了创建对象后,会默认调用其无参构造的方法,来进行默认配置的设置。
三、测试类
package com.godgy.constructor;
/**
* @author : Mr.Godgy
* @version : 1.0
* @date : 2022/11/4
* @description:
*/
public class Test {
public static void main(String[] args) {
Configure configure = new Configure();
System.out.println("无参构造的默认配置: " + configure.getConfig());
ConfigBean myConfig = new ConfigBean();
myConfig.setHost("8088");
myConfig.setServer("192.168.52.128");
myConfig.setName("myServer");
myConfig.setLanguage("en");
Configure configure1 = new Configure(myConfig);
System.out.println("我的配置: " + configure1.getConfig());
}
}
执行结果:
#第一个打印结果
无参构造的默认配置: ConfigBean(name=Tomcat, server=localhost, host=8080, language=zh_CN)
#第二个打印结果
我的配置: ConfigBean(name=myServer, server=192.168.52.128, host=8088, language=en)
感谢您的来访,获取更多精彩文章请收藏本站。
© 版权声明
THE END
暂无评论内容