小编lub*_*nac的帖子

如何通过Spring @PostConstruct初始化final变量?

我必须初始化一些最终变量,但这些值需要由 Spring Properties 读取

public class CrawlerClient{
    @Autowired
    @Qualifier("crawlerProperties")
    private Properties crawlerProperties;

    private Integer  final maxTopic;
    public static void main(String[] args) {
        //initialize();
    }
    @PostConstruct
    private void initialize(){
        List<Topic> topics = topicBusiness.getAll();
        List<Blogger> bloggers = bloggerBusiness.getAll();
        List<Clue> clues = clueBusiness.getAll();
        ClueQueue.addAll(clues);
        TopicQueue.addAll(topics);
        BloggerQueue.addAll(bloggers);

    }
..
}
Run Code Online (Sandbox Code Playgroud)

我想初始化“maxTopic”变量,但值在属性中,所以我无法在构造中执行此操作,我该怎么做?我只知道删除“final”键。最后,我是这样做的:

final Integer maxTopic;
    final Integer maxBlogger;
    final Integer maxClue;
    @Autowired
    public CrawlerClient(@Qualifier("crawlerProperties")Properties crawlerProperties){
        this.maxTopic = Integer.parseInt(crawlerProperties.getProperty("MaxTopic"));
        this.maxBlogger = Integer.parseInt(crawlerProperties.getProperty("MaxBlogger"));
        this.maxClue = Integer.parseInt(crawlerProperties.getProperty("MaxClue"));
    }
Run Code Online (Sandbox Code Playgroud)

有人能用更好的方法解决吗?

java spring dependency-injection

6
推荐指数
1
解决办法
1万
查看次数

如何配置sessionListener使用spring boot 1.x.

我是Spring Boot的新手.现在,我想添加一个监听器.
例如public MySessionListener implement HttpSessionListener
如何配置SpringApplication?我可以用SpringApplication.addListener()其他方式吗?请.

java spring servlets spring-mvc spring-boot

6
推荐指数
1
解决办法
7115
查看次数

Maven 和 spring-boot:如何在 spring-boot:repackage 上指定配置文件

使用 spring-boot,我知道我可以拥有配置文件并根据活动配置文件使用不同的配置文件。例如命令:

“mvn spring-boot:run -Drun.profiles=default,production”

将使用“application-default.properties”和“application-production.properties”中定义的设置运行我的spring-boot应用程序,第二个文件上的设置覆盖第一个文件中定义的相同设置(例如db connection设置)。所有这些目前运行良好。

但是,我想构建我的 spring-boot 应用程序并使用以下命令生成一个可运行的 jar:

“mvn 包 spring-boot:repackage”。

此命令确实可以很好地生成自包含的可运行 jar。问题是,¿如何使用前一个命令指定活动配置文件?我用过了

“mvn package spring-boot:repackage -Drun.profiles=default,production”

但它不起作用。

java spring maven spring-profiles spring-boot

6
推荐指数
2
解决办法
1万
查看次数

如何在Spring Boot应用程序启动时启动H2 TCP服务器?

通过在SpringBootServletInitializer主方法中添加以下行,当我将应用程序作为Spring Boot应用程序运行时,我能够启动H2 TCP服务器(文件中的数据库):

@SpringBootApplication
public class NatiaApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        Server.createTcpServer().start();
        SpringApplication.run(NatiaApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如果我在Tomcat上运行WAR文件它不起作用,因为没有调用main方法.在bean初始化之前,如何在应用程序启动时启动H2 TCP服务器有更好的通用方法吗?我使用Flyway(autoconfig),它在"Connection refused:connect"上失败,可能是因为服务器没有运行.谢谢.

java spring tomcat h2 spring-boot

6
推荐指数
1
解决办法
6309
查看次数

使用JPA存储库的Spring Batch ItemWriter持续存在问题

我有一个弹簧批处理问题,该批处理ItemWriter依赖JPA存储库来更新数据。

这里是:

@Component
public class MessagesDigestMailerItemWriter implements ItemWriter<UserAccount> {

    private static final Logger log = LoggerFactory.getLogger(MessagesDigestMailerItemWriter.class);

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private MailerService mailerService;

    @Override
    public void write(List<? extends UserAccount> userAccounts) throws Exception {
        log.info("Mailing messages digests and updating messages notification statuses");

        for (UserAccount userAccount : userAccounts) {
            if (userAccount.isEmailNotification()) {
                mailerService.mailMessagesDigest(userAccount);
            }
            for (Message message : userAccount.getReceivedMessages()) {
                message.setNotificationSent(true);
                messageRepository.save(message);//NOT SAVING!!
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的Step配置:

@Configuration
public class MailStepConfiguration {

    @Autowired
    private StepBuilderFactory stepBuilderFactory; …
Run Code Online (Sandbox Code Playgroud)

java spring spring-batch spring-data-jpa spring-boot

6
推荐指数
2
解决办法
5823
查看次数

如何在不影响原始bean的"客户端"的情况下声明另一个Jackson ObjectMap?

我有一个spring-boot应用程序,它公开了一个json REST API.为了将对象映射到json,它使用spring-boot配置的内置jackson ObjectMapper.

现在我需要从yaml文件中读取一些数据,我发现一个简单的方法是使用Jackson - 为此我需要声明一个不同的ObjectMapper来将yaml转换为对象.我声明这个新的mapper bean有一个特定的名称,可以在我的服务中注入它来处理从yaml文件中读取:

@Bean(YAML_OBJECT_MAPPER_BEAN_ID)
public ObjectMapper yamlObjectMapper() {
    return new ObjectMapper(new YAMLFactory());
}
Run Code Online (Sandbox Code Playgroud)

但我需要一种方法来告诉原始json ObjectMapper的所有其他"客户端"继续使用该bean.所以基本上我需要在原始bean上使用@Primary注释.有没有办法实现这一点,而无需在我自己的配置中重新声明原始的ObjectMapper(我必须挖掘spring-boot代码来查找和复制其配置)?

我找到的一个解决方案是为ObjectMapper声明一个FactoryBean并使它返回已经声明的bean,如本答案所示.我通过调试发现我的原始bean被称为"_halObjectMapper",所以我的factoryBean将搜索这个bean并返回它:

public class ObjectMapperFactory implements FactoryBean<ObjectMapper> {

    ListableBeanFactory beanFactory;

    public ObjectMapper getObject() {
        return beanFactory.getBean("_halObjectMapper", ObjectMapper.class);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后在我的Configuration类中,我将其声明为@Primary bean,以确保它是自动装配的首选:

@Primary
@Bean
public ObjectMapperFactory objectMapperFactory(ListableBeanFactory beanFactory) {
    return new ObjectMapperFactory(beanFactory);
}
Run Code Online (Sandbox Code Playgroud)

尽管如此,我对这个解决方案并不十分满意,因为它依赖于不受我控制的bean的名称,而且它看起来像是一个黑客.有更清洁的解决方案吗?

谢谢!

java spring dependency-injection jackson spring-boot

6
推荐指数
1
解决办法
2403
查看次数

用于控制器休息服务的Spring Junit测试用例

我有一个响应REST调用的控制器,我有其他公共方法的各种测试用例.

我不知道如何为我的控制器写一个:

@RequestMapping(value = "/api/frames", method = RequestMethod.GET)
public List<Frame> getFrames(
  @RequestParam(value="frameLength", required=true) Double frameLength,
  @RequestParam(value="frameBreadth", required=true) Double frameBreadth,
  @RequestParam(value="mountThickness", required=true) Double mountThickness,
  @RequestParam(value="frameThickness", required=true) Double frameThickness){
    List<Frame> tempFrames = new ArrayList<>();
    List<FrameVariant> frameVariants = frameVariantService.getFrames(
      frameLength, frameBreadth, mountThickness, frameThickness);
    for (FrameVariant frameVariant : frameVariants) {
      tempFrames.add(new Frame(frameVariant));
    }
    return tempFrames;
  }
Run Code Online (Sandbox Code Playgroud)

我不知道如何为这个控制器方法编写一个测试用例.

rest junit spring spring-mvc spring-test

5
推荐指数
1
解决办法
1万
查看次数

Node.JS to2回调

我是Node.JS的新手,并试图了解through2库.

我想知道回调(在下面的示例代码中,从上面的链接复制)是如何有用的.如果可能,请使用一小段代码解释.

fs.createReadStream('ex.txt')
  .pipe(through2(function (chunk, enc, callback) {
    for (var i = 0; i < chunk.length; i++)
      if (chunk[i] == 97)
        chunk[i] = 122 // swap 'a' for 'z' 

    this.push(chunk)

    callback()
   }))
  .pipe(fs.createWriteStream('out.txt'))
Run Code Online (Sandbox Code Playgroud)

javascript callback node.js

5
推荐指数
1
解决办法
2487
查看次数

spring-boot 中如何分离前端和后端机器?

我想将后端和前端(HTML页面)机器分开。后端将由Spring-Boot开发。如何将控制器中的视图返回到前端机器,而不是后端(Spring-Boot--->Apache Tomacat)机器中的“资源/模板”?

例如 :

@Controller
public class GreetingController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false,  defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }

}
Run Code Online (Sandbox Code Playgroud)

我想将“问候”视图放在另一台服务器(前端)中。

java spring spring-mvc spring-boot

5
推荐指数
1
解决办法
6470
查看次数

logback没有找到maven的属性project.build.directory

我有一个Spring Boot和maven的小项目,现在我正在尝试配置logback来写入文件.我希望它写入一个给定的文件${project.build.directory}/${log.folder}/logfile.log,因此构建目录的子文件夹${log.folder}是我在application.properties文件中指定的属性,放在我的/resources文件夹下.

这是我的logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <logger name="org.springframework.boot" level="INFO"/>
    <logger name="org.springframework.security" level="ERROR"/>
    <logger name="org.glassfish.jersey" level="DEBUG"/>

    <property resource="application.properties"/>

    <appender name="DUMMY_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${project.build.directory}/${log.folder}/logfile.log</file>
        <encoder>
            <pattern>%d{"yyyy-MM-dd HH:mm:ss,SSS zzz"}, [%thread] %-5level %logger{5} - %msg%n
            </pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.folder}/spring.log.%d</fileNamePattern>
        </rollingPolicy>
    </appender>

    <logger name="xxxxxx" level="INFO" additivity="false">
        <appender-ref ref="DUMMY_APPENDER"/>
    </logger>

    <root level="INFO">
        <appender-ref ref="DUMMY_APPENDER"/>
    </root>
</configuration>
Run Code Online (Sandbox Code Playgroud)

它写日志,但我的问题是,当我运行应用程序时,它会创建一个文件夹project.build.directory_IS_UNDEFINED,然后将我的log.folder放在它下面.它在文档中说,那

作为其构建工具,logback依赖于Maven,这是一种广泛使用的开源构建工具.

当在logback.xml中,我开始键入$ {pro ...然后我的IDE显示一组可用的maven隐式属性.

所以它应该有效,但事实并非如此.知道为什么吗?

spring properties logback maven spring-boot

5
推荐指数
2
解决办法
3195
查看次数