1、通过@Value的方式
package com.ec.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "MyBean{" +
"name='" + name + '\'' +
'}';
}
@Value("${name}")
private String name;
}
package com.ec.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@EnableConfigurationProperties(Mail.class)
@RestController
@SpringBootApplication
public class DemoApplication {
@Autowired
private MyBean myBean;
@Autowired
private Mail mail;
@RequestMapping("/")
String home() {
return myBean.toString();
}
@RequestMapping("/mail")
String mail() {
// Mail mail = new Mail();
return mail.toString();
}
public static void main(String[] args) throws Exception {
SpringApplication.run(DemoApplication.class, args);
}
}
2、通过@ConfigurationProperties的方式
package com.ec.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "mail")
public class Mail {
private String name;
private String secret;
private Integer ssl;
@Override
public String toString() {
return "Mail{" +
"name='" + name + '\'' +
", secret='" + secret + '\'' +
", ssl=" + ssl +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public Integer getSsl() {
return ssl;
}
public void setSsl(Integer ssl) {
this.ssl = ssl;
}
}
注意,要在主类中添加@EnableConfigurationProperties(Mail.class)
,而且两种方式都要通过@Autowired的方式注入对象,不能自己new
登陆发表评论