2016-05-23 4 views
0

私は便利なマイクロサービスと呼ばれる小さなサービスをたくさん持っています;-)、それらはすべて同じスタートアップ動作を持っています。それらはパッケージにまとめられています - パッケージはそれぞれ1つのサービスに対応しています。パッケージの命名は、このようなものです:java getクラスのクラス

com.fooは、ドメイン部分である
com.foo.bar.Application 

は、バーには、実際のサービス名で、アプリケーションは、mainメソッドを持つ私のメインのインスタンスクラスです。

私がやりたかったのは、標準化されたログメッセージが表示されたときに印刷し、ユーザーがサービスに関する情報を得るために照会できるURLを表示することです。定義ごとのサービスのために関する情報を取得するためのURLは次のように構築されなければならない:

IP:PORT/bar/admin/info 

私ははgetClass()...などと、このbar.nameを取得しようとしましたが、それは動作しません。だから私はこの試みた:

LOG.info("Access URLs:\n----------------------------------------------------------\n" + 
      "\tLocal: \t\thttp://127.0.0.1:{}/" + getMyClass() + "/info\n" + 
      "\tExternal: \thttp://{}:{}/" + getMyClass() + "/info\n----------------------------------------------------------", 
       env.getProperty("server.port"), 
       InetAddress.getLocalHost().getHostAddress(), 
       env.getProperty("server.port") 
     ); 

/** 
    * Get the name of the application class as a static value, so we can show it in the log 
    */ 
    public static final Class[] getClassContext() { 
     return new SecurityManager() { 
      protected Class[] getClassContext(){return super.getClassContext();} 
     }.getClassContext(); 
    }; 
    public static final Class getMyClass() { return getClassContext()[2];} 

をしかし、あなたは既に推測しているかもしれませんが、これはあまりにも多く出て印刷します。私は取得したいのですが、すべてが

bar 

ある

class com.foo.bar.Application 

どうすればこれを達成できますか?

ちなみに、私は、Java 8と春ブーツを使用している - それは

敬具、

クリス

答えて

1

あなた可能性最初にクラスからパッケージオブジェクトを取得してから、その名前を読み取ります。だから、

String packageName = getMyClass().getPackage().getName(); 

    String directParent; 
    if(packageName.contains(".")) { 
     directParent = packageName.substring(1 + packageName.lastIndexOf(".")); 
    } else { 
     directParent = packageName; 
    } 

:次のコードは、directParent変数にpackageName変数であり、直接の親の名前(のようなbar)(例えば、「com.foo.bar」のように)あなたの完全含むパッケージ名を与えますこのスニペットの後に置くと、あなたのログステートメントはこれらの変数のいずれかを使用することができます。

+0

こんにちはアーネスト、ありがとう。それはそれを解決しました! – siliconchris

1

を助けている場合、このような何か:

String pack = getClass().getPackage().getName(); 
String[] split = pack.split("\\."); 
pack = split[split.length-1]; 
+0

[Class.getPackage](https://docs.oracle.com/javase/8/docs/api/java /lang/Class.html#getPackage--)はnullを返すことができます。この場合、完全修飾クラス名を解析するだけで済みます。 – jmehrens

0

アーネストのおかげで、それは完璧に動作します。以下 同じ要件を有することができる他のすべてのために、私は投稿します私のコード:

@ComponentScan(basePackages = "com.foo.fileexportservice") 
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, LiquibaseAutoConfiguration.class}) 
@EnableEurekaClient 
@EnableCircuitBreaker 
@EnableFeignClients(basePackages = "com.foo.fileexportservice") 
public class Application { 

    private static final Logger LOG = LoggerFactory.getLogger(Application.class); 
    private static final String ERROR_MSG = "You have misconfigured your application! "; 

    @Inject 
    private Environment env; 

    /** 
    * Main method, used to run the application. 
    */ 
    public static void main(String[] args) throws UnknownHostException { 
     SpringApplication app = new SpringApplication(Application.class); 
     app.setShowBanner(true); 
     SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); 
     addDefaultProfile(app, source); 
     Environment env = app.run(args).getEnvironment(); 
     LOG.info("Access URLs:\n----------------------------------------------------------\n" + 
      "\tLocal: \t\thttp://127.0.0.1:{}/" + getPackageName() + "/admin/info\n" + 
      "\tExternal: \thttp://{}:{}/" + getPackageName() + "/admin/info\n----------------------------------------------------------", 
       env.getProperty("server.port"), 
       InetAddress.getLocalHost().getHostAddress(), 
       env.getProperty("server.port") 
     ); 

    } 

    /** 
    * Get the name of the application class as a static value, so we can show it in the log 
    */ 
    private static final String getPackageName() { 
     String packageName = getMyClass().getPackage().getName(); 

     String directParent; 
     if(packageName.contains(".")) { 
      directParent = packageName.substring(1 + packageName.lastIndexOf(".")); 
     } else { 
      directParent = packageName; 
     } 
     return directParent; 
    }; 
    private static final Class[] getClassContext() { 
     return new SecurityManager() { 
      protected Class[] getClassContext(){return super.getClassContext();} 
     }.getClassContext(); 
    }; 
    private static final Class getMyClass() { return getClassContext()[2];} 


    /** 
    * If no profile has been configured, set by default the "dev" profile. 
    */ 
    private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { 
     if (!source.containsProperty("spring.profiles.active") && 
       !System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) { 

      app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT); 
     } 
    } 
}