小编Eri*_* B.的帖子

exec-maven-plugin arguments 和 commandlineArgs 之间的区别

我正在尝试将 exec-maven-plugin 与java目标一起使用。但是,我对这两个选项之间的区别感到困惑:

  • 争论
  • 命令行参数

如果我尝试使用参数,对我的 java 类的调用将失败。

我的班级被调用的签名是:

 public static void main(String[] args)
  {
    VeracodeParser parser = new VeracodeParser();
    parser.parse(args);
  }
Run Code Online (Sandbox Code Playgroud)

我的pom:

        <plugin>
            <artifactId>exec-maven-plugin</artifactId>
            <groupId>org.codehaus.mojo</groupId>
            <executions>
                <execution>
                    <id>Zip packaging and deployment</id>
                    <phase>process-sources</phase>
                    <goals>
                        <goal>java</goal>
                    </goals>
                    <configuration>
                        <mainClass>com.veracode.apiwrapper.cli.VeracodeCommand</mainClass>
                        <arguments>
                            <argument>-action GetAppList</argument>
                            <argument>-vuser ${veracode.username}</argument>
                            <argument>-vpassword ${veracode.password}</argument>
                        </arguments>
                    </configuration>
                </execution>
            </executions>
        </plugin>
Run Code Online (Sandbox Code Playgroud)

但是,我从 VeracodeCommand 类收到错误消息,表明我缺少-action,-vuser-vpassword参数。

但是,当我将其切换为使用单个字符串commandlineArgs参数时,它按预期工作:

        <plugin>
            <artifactId>exec-maven-plugin</artifactId>
            <groupId>org.codehaus.mojo</groupId>
            <executions>
                <execution>
                    <id>Zip packaging and deployment</id>
                    <phase>process-sources</phase>
                    <goals>
                        <goal>java</goal>
                    </goals>
                    <configuration>
                        <mainClass>com.veracode.apiwrapper.cli.VeracodeCommand</mainClass>
                        <commandlineArgs>-action …
Run Code Online (Sandbox Code Playgroud)

java maven exec-maven-plugin

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

如何从注释中获取Spring配置文件名称?

使用Spring 3.1和配置文件,创建用于定义特定配置文件的自定义界面变得很有趣。美丽的部分原因是能够完全忘记配置文件的字符串名称,而仅使用注释。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("Dev")
public @interface Dev {

}
Run Code Online (Sandbox Code Playgroud)

然后只需使用注释豆@Dev。这很好。

但是,如何检查@Dev配置文件是否处于活动状态? Environment.acceptsProfiles()需要一个String参数。有没有一种“整洁”的方式来做到这一点,或者我做这件事的唯一选择是:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile(Dev.NAME)
public @interface Dev {
    public static String NAME = "Dev";
}


public class MyClass{

    @Autowired
    private Environment env;

    private void myMethod(){
       if( env.acceptsProfiles( Dev.NAME ) )
          // do something here
        ;
    }
Run Code Online (Sandbox Code Playgroud)

尽管功能强大,但我并不特别喜欢这个概念。还有其他方法可以使我更整洁吗?

java spring

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

在SpringBoot应用程序启动时捕获Hibernate异常吗?

我正在尝试将Spring Boot 1.2.6与结合使用HibernateJpaAutoConfiguration。效果很好;这是由entityManager“神奇地”创建的,并使用spring.jpa。*属性为我完成了所有配置。

但是,在发生数据库错误(无效的凭据,无法访问数据库等)的情况下,我无法找到一种干净的方法来在启动时捕获Hibernate异常。

我以为我可以捕获所有BeanCreationException并检查根本原因,但这似乎是很简单的事情:

    ConfigurableApplicationContext context;
    try {
        SpringApplication app = new SpringApplication(Application.class);
        context = app.run(args);
    } catch (Exception e) {
        // check if it is a DB error.  
        if( ExceptionUtils.getRootCause(e) instanceof( HibernateException ) ){
            System.out.println( "You are having trouble with the DB: " + ExceptionUtils.getRootCauseMessage(e) );
        }
    }
    finally{
        // finished so close the context
        if( context != null )
            context.close();
    }
Run Code Online (Sandbox Code Playgroud)

是否有一种更干净/更整洁的方式来执行此操作,而又不会失去使用自动配置的功能?另外,除了解析错误消息外,还有一种方法可以确定什么是Hibernate / DB错误(即:无效的凭据,未验证的DB等)。

java spring hibernate spring-boot

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

如何使用maven-bundle-plugin从Import-Package中排除版本号?

我遇到了maven-bundle-plugin生成的MANIFEST.MF问题.出于某种原因,当我在<Import-Package>字段中列出版本号时,OSGi框架不会加载我的包.

我已经尝试并注意到如果我删除清单中的版本号,那么捆绑包已正确加载.

如何指示maven-bundle-plugin跳过版本号?

目前,它生成:

Import-Package: com.ghc.ghTester.expressions,org.apache.ws.security.proc
 essor;version="[1.5,2)",org.apache.ws.security;version="[1.5,2)",org.ap
 ache.ws.security.message;version="[1.5,2)",org.apache.ws.security.compo
 nents.crypto;version="[1.5,2)",org.apache.ws.security.message.token;ver
 sion="[1.5,2)"
Run Code Online (Sandbox Code Playgroud)

但我需要它来生成:

Import-Package:com.ghc.ghTester.expressions,org.apache.ws.security.proc essor,org.apache.ws.security,org.apache.ws.security.message,org.apache.ws.security.components.crypto,org.apache.ws.security.message.token

我的插件配置是:

        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>3.0.0</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>${pom.groupId}.${pom.artifactId};singleton:=true</Bundle-SymbolicName>
                    <Bundle-Name>${pom.name}</Bundle-Name>
                    <Bundle-Version>${pom.version}</Bundle-Version>
                    <Bundle-ClassPath>{maven-dependencies},.</Bundle-ClassPath>
                    <Embed-Dependency>*;scope=compile</Embed-Dependency>
                    <Export-Package/> <!-- nothing for this bundle to export -->
                    <Import-Package>com.ghc.ghTester.expressions,org.apache.ws.*</Import-Package>
                </instructions>
            </configuration>
        </plugin>
Run Code Online (Sandbox Code Playgroud)

如果我尝试加载版本,我会收到以下错误:

org.osgi.framework.BundleException: Could not resolve module: com.rit.message-level-security [978]
  Unresolved requirement: Import-Package: org.apache.ws.security; version="[1.0.0,3.0.0)"

        at org.eclipse.osgi.container.Module.start(Module.java:434)
        at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:393)
        at org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:412)
        at com.ghc.ghTester.Activator.installTempBundle(Activator.java:157)
Run Code Online (Sandbox Code Playgroud)

osgi eclipse-plugin maven apache-felix

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

记录EJB RMI调用

是否有可以用于RMI调用的类似于RequestListener的东西?通过RMI调用加载EJB时,有什么方法可以将上下文信息注入到log4j MDC中?

我有一个Web应用程序,其中包含通过EJB实现的所有业务逻辑。我的EJB使用Log4j创建日志条目。

在请求侦听器中,我向Log4j MDC添加了一些特定的参数(例如请求ID,会话ID等),这些参数由附加程序自动插入。

public class Log4jMDCRequestListener implements ServletRequestListener {
    /**
     * Inject the necessary trackers into the MDC to use in the log4j loggers
     */
    @Override
    public void requestInitialized(ServletRequestEvent paramServletRequestEvent) {

        HttpServletRequest request = (HttpServletRequest) paramServletRequestEvent.getServletRequest();

        // generate a random requestId to correlate all logs from the same request
        String requestId = RandomStringUtils.randomAlphanumeric(32);
        MDCUtils.setRequestId(requestId);

        // inject the username and ip into the MDC as well for use in some logs
        MDCUtils.setUsername(RequestUtils.getLoginUserName(request));
        MDCUtils.setIP(RequestUtils.getRealIP(request));
    }
}
Run Code Online (Sandbox Code Playgroud)

log4j.xml:

 <layout class="org.apache.log4j.PatternLayout">
   <param …
Run Code Online (Sandbox Code Playgroud)

java rmi java-ee

5
推荐指数
0
解决办法
207
查看次数

Mapstruct注释处理器在Intellij中似乎不适用于Gradle项目

我正在尝试使用Intellij 2017 Ultimate来构建/运行使用MapStruct的Spring Boot应用程序.这是Gradle项目.我的问题是IntelliJ似乎没有运行MapStruct注释处理器.我意识到我可以将IntelliJ配置为委托给Gradle构建过程(参见本节),但我希望简单地配置IntelliJ以使用APT自己生成必要的类.

我为我的项目启用了APT,但我的类仍未生成.

build.gradle(适用的代码段):

ext {
    mapstructVersion = '1.2.0.Final'
}

plugins {
    id 'net.ltgt.apt' version '0.15'
}

dependencies {
    // MapStruct support
    implementation group: 'org.mapstruct', name: 'mapstruct-jdk8', version: mapstructVersion
    annotationProcessor group: 'org.mapstruct', name: 'mapstruct-processor', version: mapstructVersion
 }
Run Code Online (Sandbox Code Playgroud)

IntelliJ配置:

在此输入图像描述

然而,当我执行./gradle clean后面的Build-> Rebuild Project时,我的out/production/classes/generated文件夹是空的.

在这个项目上启用APT需要做些什么吗?IntelliJ应该自动检测类路径中的mapstruct注释处理器吗?

java intellij-idea gradle mapstruct

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

JCache 具有多个缓存提供程序?

我故意在我的类路径中添加了几个不同的缓存提供程序。我有用于分布式缓存的 Hazelcast 和用于本地缓存的 Caffeine。我正在尝试使用 JCache (JSR107) 注释来缓存我的值。

我已经创建了一个 CacheResolverFactory ,它将能够检测要从哪个提供程序使用哪个缓存管理器(基于方法注释),但是当我启动应用程序时,我收到以下错误消息:

Exception in thread "Thread-2" javax.cache.CacheException: Multiple CachingProviders have been configured when only a single CachingProvider is expected
    at javax.cache.Caching$CachingProviderRegistry.getCachingProvider(Caching.java:386)
    at javax.cache.Caching$CachingProviderRegistry.getCachingProvider(Caching.java:361)
    at javax.cache.Caching.getCachingProvider(Caching.java:151)
    at org.jsr107.ri.annotations.DefaultCacheResolverFactory.<init>(DefaultCacheResolverFactory.java:59)
    at org.jsr107.ri.annotations.cdi.CacheLookupUtil.<init>(CacheLookupUtil.java:45)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
Run Code Online (Sandbox Code Playgroud)

显然,我知道我有多个缓存提供程序。但是,我似乎无法找到有关此问题的任何信息。该类org.jsr107.ri.annotations.cdi.CacheLookupUtil有一个私有 CacheResolverFactory 成员,该成员在构造时初始化为需要单个 CacheProvider 的 DefaultCacheResolverFactory()。

public class CacheLookupUtil extends AbstractCacheLookupUtil<InvocationContext> {
    @Inject
    private BeanManagerUtil beanManagerUtil;
    private CacheKeyGenerator defaultCacheKeyGenerator = new DefaultCacheKeyGenerator();
    private CacheResolverFactory defaultCacheResolverFactory = new DefaultCacheResolverFactory();
...
...
}
Run Code Online (Sandbox Code Playgroud)

我可以做些什么来避免这个问题吗?JCache …

java jcache jsr107

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

如何将 Picocli 解析的参数注入到 Spring Bean 定义中?

我正在尝试将Picocli与 Spring Boot 2.2 结合使用,将命令行参数传递给 Spring Bean,但不确定如何构造它。例如,我有以下@Command命令从命令行指定连接用户名和密码,但是我想使用这些参数来定义 Bean:

@Component
@CommandLine.Command
public class ClearJdoCommand extends HelpAwarePicocliCommand {
    @CommandLine.Option(names={"-u", "--username"}, description = "Username to connect to MQ")
    String username;

    @CommandLine.Option(names={"-p", "--password"}, description = "Password to connect to MQ")
    String password;

    @Autowired
    JMSMessagePublisherBean jmsMessagePublisher;

    @Override
    public void run() {
        super.run();
        jmsMessagePublisher.publishMessage( "Test Message");
    }
}


@Configuration
public class Config {
    @Bean
    public InitialContext getJndiContext() throws NamingException {
        // Set up the namingContext for the JNDI lookup
        final Properties env …
Run Code Online (Sandbox Code Playgroud)

spring-boot picocli

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

战争中的一个班级有没有办法从它的耳边接入META-INF?

这种需求可能听起来有点复杂,如果是这样,那么我愿意接受关于实施最佳实践的建议.我的问题如下.我有一个WAR webapp,它包含在EAR中.一切都是青春的.从我的webapp中,我试图显示耳朵和战争的神器ID和版本号.

战争是一个相当容易处理的案件.我可以使用简单的maven过滤在构建战争时将必要的artifactId/versionId注入到战争中.然而,耳朵更复杂.

我知道有一个META-INF/maven /// pom.properties,我可以在耳边看到包含该信息,但我看不到它.

我已经尝试(从jsp页面内)以下内容但没有成功(所有有和没有前导/); 所有调用都返回null:

getClass().getClassLoader().getResource( "/META-INF/maven/<group>/<artifact>/pom.properties");
getClass().getClassLoader().getResourceAsStream( "/META-INF/maven/<group>/<artifact>/pom.properties");
Run Code Online (Sandbox Code Playgroud)

这甚至可以使用类加载器吗?或者是类加载器配置依赖吗?有没有更好的方法来获取此信息?

我目前正在JBoss上运行测试,但最终的部署将在WebSphere上进行.但是,理想情况下,我想要一个不依赖于服务器的解决方案.

谢谢!

埃里克

java ear war pom.xml maven

4
推荐指数
1
解决办法
1972
查看次数

无论如何@ Inject/@将内部类自动装入一个外部类?

在Spring/JSR-330中,有没有办法正确声明需要依赖注入的内部类,这样我可以将它注入外部类?

例如:

@Component
public class TestClass{

    // How to declare this class?
    private class TestClassInner{
       @Autowired private SomeBean somebean;

       public boolean doSomeWork(){
          return somebean.doSomething();
       }               
    }

    // Inject the inner class here in the outer class such that the outer class can use an instance of it
    @Autowired TestClassInner innerClass;

    @PostConstruct
    public void init(){
        ...
    }

    public void someMethod(){
       innerClass.doSomeWork();
       ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用@Component注释内部类,使其成为公共类,使其成为公共静态等,但似乎我尝试过的每个组合总是会抛出一个或另一个错误.

作为一个私有内部类,Spring抱怨它缺少一个构造函数,即使我定义了一个.

作为一个带注释的@Component公共静态类,Spring抱怨它找到了两个bean - TestClass @ TestClassInner和testClass.TestClassInner.如果我使用a @Qualifier,它会抱怨无法找到bean.

我认为我误解了这些内部bean如何工作/与Spring交互以正确理解是否/如何声明它们.

这甚至可能吗?

编辑

所以这里有一些我尝试过的组合(包括尝试实现基于@SotiriosDelimanolis响应的新构造函数):

    // How …
Run Code Online (Sandbox Code Playgroud)

java spring dependency-injection

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