Spring可以初始化“非bean”字段吗?

时间:2009-05-07 19:27:25

标签: java spring

我初始化了一个java.util.logging.Logger bean,现在想要添加一个Handler,我也为它创建了一个bean。问题是Logger方法被称为addHandler,而不是setHandler

如何将处理程序注入记录器?

我是否需要将Logger包装在Spring友好的bean类中?

修改

如果有人也可以告诉我如何传递记录级别(这是一个静态值),我将非常感激。

1 个答案:

答案 0 :(得分:4)

更新:更改为使用java.util.logging,并显示如何设置级别。

您可以通过实施FactoryBean来使用此功能:

package foo.bar;

import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Logger;

import org.springframework.beans.factory.FactoryBean;

public class LoggerFactoryBean implements FactoryBean {

    private final Logger logger;

    public LoggerFactoryBean(java.util.logging.Logger logger,
            List<Handler> handlers) {
        this.logger = logger;
        for (Handler handler : handlers) {
            logger.addHandler(handler);
        }
    }

    @Override
    public Object getObject() throws Exception {
        return logger;
    }

    @Override
    public Class getObjectType() {
        return Logger.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

然后在XML中定义您的bean,如:

  <!-- returns logger with handlers -->
  <bean id="logger" class="foo.bar.LoggerFactoryBean">
    <constructor-arg>
      <!-- raw logger without handlers -->
      <bean class="java.util.logging.Logger" factory-method="getAnonymousLogger">
        <property name="level">
          <value>SEVERE</value>
        </property>
      </bean>
    </constructor-arg>
    <constructor-arg>
      <util:list>
        <bean class="java.util.logging.FileHandler" />
      </util:list>
    </constructor-arg>
  </bean>

单元测试示例:

package foo.bar;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "classpath:/foo/bar/test-config.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class HandlerTest {

    @Autowired
    private Logger logger;

    @Test
    public void testLogger() {
        assertNotNull(logger);
        assertEquals(Level.SEVERE, logger.getLevel());
    }
}