我目前有一个内部使用的自定义日志管理器java.util.Formatter.主要问题是它不是很有用:每个应用程序在一个文件中的所有内容,无法在数据库中添加特定日志,无法发送邮件,......
所以我希望能够增加我们的日志记录系统的功能.经过几次测试后,Log4J正是我现在所需要的.但是我想避免将来再次重新改变它的痛苦,所以我打算在Log4J上使用slf4j.
即使我已准备好在我的所有代码库中进行大搜索/替换以使用slf4j,我还没准备好检查每个日志语句并重新格式化它以使用{}slf4j 的格式.
所以我的问题是:如何使用slf4j接口并告诉它内部应该使用a java.util.Formatter而不是默认值,最好是在一个地方(意味着不在每个类或包中)?
注意:所有关于表演的答案或说我不应该使用juFormatter的答案都将被抛弃:我需要一个务实的解决方案来解决我的问题,而不是开始辩论.
我想检查ResourceBundle的存在而不实际加载它.
通常,我正在使用Guice,并且在初始化时,我想检查存在,而在执行时,我想加载它.如果捆绑不存在,我想要早期报告RB的不存在.
如果有可能获得用于特定ResourceBundle的ResourceBundle.Control实例,我将获得构建实际资源名称的基本信息(使用toBundleName()和toResourceName())没有问题,但事实并非如此.那个级别.
编辑:
好的,我找到了办法.我将创建一个可扩展的ResourceBundle.Control(使用custom addFormat(String,Class))来存储所有包格式,然后使用我自己的另一种方法检查特定语言环境的所有可能的文件名(使用Class. getResource,如下所示).
编码说:
class MyControl extends ResourceBundle.Control {
private Map<String,Class<? extends ResourceBundle>> formats = new LinkedHashMap();
public void addFormat(String format,Class<? extends ResourceBundle> rbType) {
formats.put(format, rbType);
}
public boolean resourceBundleExists(ClassLoader loader, String baseName, Locale locale) {
for (String format: formats.keySet()) {
// for (loop on locale hierarchy) {
if (loader.getResource(toResourceName(toBundleName(baseName, locale), format)) != null) {
return true;
}
// }
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud) 假设我有以下可能无法修改的Java接口:
public interface MyInterface {
public void doSomething();
}
Run Code Online (Sandbox Code Playgroud)
现在实现它的类是这样的:
class MyImplementation implements MyInterface {
public void doSomething() {
try {
// read file
} catch (IOException e) {
// what to do?
}
}
}
Run Code Online (Sandbox Code Playgroud)
我无法从不读取文件中恢复.
一个子类RuntimeException可以明显帮助我,但我不确定这是否是正确的做法:问题是该异常将不会在类中记录,并且该类的用户可能会得到该异常解决这个问题.
我能做什么?
我们都同意:接口有问题.
我选择的解决方案
我最终决定编写一个MyVeryOwnInterface扩展MyInterface并添加作为错误方法签名的一部分MyRuntimeException:
public interface MyVeryOwnInterface extends MyInterface {
public void doSomething() throws MyRuntimeException;
}
class MyImplementation implements MyVeryOwnInterface {
public void doSomething() throws MyRuntimeException {
try {
// read file …Run Code Online (Sandbox Code Playgroud) 好吧,我知道我的计算是不客观的等等,但无论如何,我讨厌在执行我的单元测试时等待这么多时间:
我的guice swing应用程序初始化大约需要7秒钟.这是一个简单的IRC客户端.那时,没有连接打开,我甚至还没有调用任何java.io或java.net类.我试图缩小究竟是什么错误,我得到了Guice使用的5.8秒(平均值),以便用我正在使用的2个模块创建注入器(一个普通模块,一个内置FactoryModuleBuilder,安装在原始模块).
当我删除所有模块(所以基本上只调用和完全调用Guice.createInjector())时,它仍然需要3.5秒.
我使用的Guice版本是3.0 rc2.我的电脑肯定不是最新的,但它仍然不超过3年.
那么如果可能的话,我怎样才能提高Guice的表现呢?
作为参考,这是我正在使用的主要方法,导致3.5秒.后续通话需要0.01秒
public static void main(String[] args) {
long t = System.currentTimeMillis();
Injector injector = Guice.createInjector();
long t1 = System.currentTimeMillis();
System.out.println(((t1 - t)) / 1000.0);
}
Run Code Online (Sandbox Code Playgroud)
结果
3.578
Run Code Online (Sandbox Code Playgroud) 我有这个bash脚本:
ACTIVE_DB=$(grep -P "^[ \t]*db.active" config.properties | cut -d= -f2 | tr -s " ")
echo $ACTIVE_DB
if [ "$ACTIVE_DB" = "A" ]
then
ln -sf config-b.properties config.properties
else
ln -sf config-a.properties config.properties
fi
Run Code Online (Sandbox Code Playgroud)
config-a.properties
db.active = A
Run Code Online (Sandbox Code Playgroud)
config-b.properties
db.active = B
Run Code Online (Sandbox Code Playgroud)
当我运行脚本时,执行硬拷贝(= cp)并且config.properties通常不是符号链接(也不是物理链接),而是具有与config-a.properties或相同内容的全新文件config-b.properties.
$ ls -li
53 -rw-r--r-- 1 ogregoir ogregoir 582 Sep 30 15:41 config-a.properties
54 -rw-r--r-- 1 ogregoir ogregoir 582 Sep 30 15:41 config-b.properties
56 -rw-r--r-- 1 ogregoir ogregoir …Run Code Online (Sandbox Code Playgroud) 这只是一个没有具体应用的理论问题.
我有以下方法,我不会碰.它可以(如果可能的话)用作BiConsumer.
void doSmallThing(A a, B b) {
// do something with a and b.
}
void doBigThing(List<A> as, B b) {
// What to do?
}
Run Code Online (Sandbox Code Playgroud)
我怎么能反覆as,同时保持b恒定,使用this::doSmallThing的doBigThing?
当然以下不起作用.
void doBigThing(List<A> as, B b) {
as.stream()
.forEach(this::doSmallThing);
}
Run Code Online (Sandbox Code Playgroud)
以下工作很好,实际上是我每天使用的.
void doBigThing(List<A> as, B b) {
as.stream()
.forEach(a -> doSmallThing(a, b));
}
Run Code Online (Sandbox Code Playgroud)
以下也适用,但有点棘手.
Consumer<A> doSmallThingWithFixedB(B b) {
return (a) -> doSmallThing(a, b);
}
void doBigThing(List<A> as, B b) {
as.stream()
.forEach(doSmallThingWithFixedB(b)) …Run Code Online (Sandbox Code Playgroud) 我有一些资源处理方法,其中包含带有的数十个@QueryParam参数@Default,并按大致主题(分页/排序,过滤,身份验证)分组。这确实很麻烦,我想简化一下。好消息是这些参数按主题(分页,排序,过滤等)分组,因此我可以将整个参数集简化为4种方法。
我该如何实现?
通常,我想从这里得出:
@GET
public Response findAll(
@QueryParam("sort") @DefaultValue("name") List<String> sort,
@QueryParam("from") UUID fromId
) {
// Validate sort
// Validate fromId
}
Run Code Online (Sandbox Code Playgroud)
对此:
@GET
public Response findAll(@Context Pagination pagination) { // Inject pagination
// Yeah, small code! Yeah, modularity!
}
// Create the pagination somewhere else.
public Pagination createPagination(@Context UriInfo uriInfo) {
Optional<UUID> fromId = extractFromId(uriInfo); // retrieve "from" from uriInfo
List<String> sort = extractSort(uriInfo); // retrieve "sort" from uriInfo
Pagination pagination = new Pagination(); …Run Code Online (Sandbox Code Playgroud) 我有以下课程:
public FooDAO extends AbstractDAO<Foo> { // Dropwizard DAO
@Inject FooDAO(SessionFactory sf) { super(sf); }
public void foo() { /* use SessionFactory */ }
}
public class FooService {
private final FooDAO fooDAO; // Constructor-injected dependency
@Inject FooService (FooDAO fooDAO) { this.fooDAO = fooDAO; }
@UnitOfWork
public void foo() {
this.fooDAO.foo();
System.out.println("I went through FooService.foo()");
}
}
Run Code Online (Sandbox Code Playgroud)
现在,FooService不是资源,因此 Dropwizard 不知道它并且不会自动代理它。然而,Dropwizard 的聪明人做到了,所以我可以通过UnitOfWorkAwareProxyFactory.
我尝试使用拦截器将这些代理提供给 Guice,但我遇到了一个问题,因为UnitOfWorkAwareProxyFactory只创建新实例并且从不让我传递现有对象。新实例的问题是我不知道要给它的参数,因为它们是由 Guice 注入的。
如何创建@UnitOfWork现有对象的感知代理?
这是我迄今为止制作的拦截器:
public class UnitOfWorkModule extends AbstractModule …Run Code Online (Sandbox Code Playgroud) 刚刚在 Java 15 中遇到了一个新特性,即“文本块”。我可以假设一个变量可以通过与“+”运算符连接来添加到文本块中,如下所示:
String html = """
<html>
<body>
<p>Hello, """+strA+"""</p>
</body>
</html>
""";
Run Code Online (Sandbox Code Playgroud)
但是他们是否提供了任何方式,以便我们可以以在许多其他语言中流行的方式添加变量,如下所示:
String html = """
<html>
<body>
<p>Hello, ${strA}</p>
</body>
</html>
""";
Run Code Online (Sandbox Code Playgroud)
这个问题可能听起来很愚蠢,但在某些情况下可能很有用。
我使用Google HTTP Client Library for Java来制作简单的JSON请求并解析响应.当我不通过代理时,它运作良好.但现在我想允许我的用户在我的应用程序中使用代理(带身份验证)功能.我查看了HttpTransport,HttpRequestFactory和HttpRequestInitializer类没有任何成功.
到目前为止,我只略微修改了这些示例(主要是它删除了不必要的代码).那么我在代码中添加了代理设置?
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
<T> T get(String url, Class<T> type) throws IOException {
HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url));
return request.execute().parseAs(type);
}
Run Code Online (Sandbox Code Playgroud)