注入userProperties,获取对应配置文件的具体值
注入需要注入的类,注入的类需加注解@Repository或@Component、@Service、@Controller
package com.xjt.demo.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnClass(UserService.class)
@EnableConfigurationProperties(UserProperties.class)
public class UserAutoConfiguration {
@Autowired
UserProperties userProperties;
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService userService(){
//将userService的字段赋值并注入到ioc容器
return new UserService(userProperties.getUserName(), userProperties.getHobby());
}
}
==============================================================================
测试类,从新项目导入注入UserService测试类方法
package com.xjt.demo.conf;
import lombok.AllArgsConstructor;
import lombok.Data;