我注意到Spring Boot应用程序类可以扩展其他类,但是main(String[] args)方法通常都使用SpringApplication.run(Application.class, args)。这些示例通常在Application类定义之上使用不同的注释。
此操作要求对三个密切相关的问题进行简单总结:
1.)Spring Boot Application.java类可以扩展哪些类?
2.)每个扩展选项的预期用途是什么?
3.)对给定扩展的选择是否也规定了必须添加到类定义中的特定注释?
根据我的研究,我确定了以下三个扩展选项:
1.)完全不扩展,如下例所示:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}2.)扩展WebMvcConfigurerAdapter,如下所示:
@SpringBootApplication
@Controller
public class UiApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(UiApplication.class, args);
}
}3.)扩展SpringBootServletInitializer,如下所示:
@Configuration
@EnableAutoConfiguration
@EnableScheduling
@ComponentScan
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String... args) {
System.setProperty("spring.profiles.default", System.getProperty("spring.profiles.default", "dev"));
final ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
}
}请注意,我保留了示例中的注释和最少的其他内容。此操作简单地询问扩展的选择是否规定了特定的注释选择或最少的其他内容。
发布于 2016-04-10 09:34:27
另一个不是继承,而是它的组合,是实现CommandLineRunner接口,以便在Spring Boot应用程序启动时执行一些操作,如下所示:
@SpringBootApplication
public class DevopsbuddyApplication implements CommandLineRunner {
/** The application logger */
private static final Logger LOG = LoggerFactory.getLogger(DevopsbuddyApplication.class);
@Autowired
private UserService userService;
@Value("${webmaster.username}")
private String webmasterUsername;
@Value("${webmaster.password}")
private String webmasterPassword;
@Value("${webmaster.email}")
private String webmasterEmail;
public static void main(String[] args) {
SpringApplication.run(DevopsbuddyApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
User user = UserUtils.createBasicUser(webmasterUsername, webmasterEmail);
user.setPassword(webmasterPassword);
Set<UserRole> userRoles = new HashSet<>();
userRoles.add(new UserRole(user, new Role(RolesEnum.ADMIN)));
LOG.debug("Creating user with username {}", user.getUsername());
userService.createUser(user, PlansEnum.PRO, userRoles);
LOG.info("User {} created", user.getUsername());
}
}我不确定这是不是你要找的。
https://stackoverflow.com/questions/36508771
复制相似问题