Spring Bean未加载并注入JAAS

时间:2017-04-28 20:08:04

标签: spring mongodb spring-boot dependency-injection

我正在尝试将Spring UserRepository加载到我的LoginModule,但是容器没有加载它。对我来说,似乎LoginContext使用提供给LoginContext的配置文件通过动态加载来加载LoginModule。因为这是由JVM加载的,所以容器因此忽略了LoginModule,尽管我已经尝试过@Component,@ Service,@ Configurable的注释,请帮忙。

JUnit测试

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@ComponentScan("com.kashtech.jaas")
public class JaasLoginModuleTests {
...
@Before
public void initialize() {

    System.setProperty("java.security.auth.login.config", "ebay-manager-jaas.config");      
    try {
        lc = new LoginContext("EbayManagerLoginModule", new JaasCallBackHandler("test", "test"));

    } catch (LoginException e) {
        e.printStackTrace();
    }
}
@Test
public void testLogin() {

    try {
        lc.login();
    } catch (LoginException le) {
        log.error("Error whilst testing login : " + le.getMessage());
    }
}

的LoginModule

import com.kashtech.jaas.repository.mongodb.UserRepository;

public class JaasLoginModule implements LoginModule {   

@Inject
private UserRepository userRepository;

....

//find user from DB
dbUser = findUserFromDB(username);

public User findUserFromDB(String username) {               
    User u = userRepository.findByUsername(username);
    return u;
    }
}

ApplicationConfiguration

@SpringBootApplication
@ComponentScan("com.kashtech.jaas")
@EnableMongoRepositories(basePackages = "com.kashtech.jaas.repository.mongodb")
public class JaasSystemApplication {

public static void main(String[] args) {
    SpringApplication.run(JaasSystemApplication.class, args);
    }
}

存储库

import org.springframework.data.mongodb.repository.MongoRepository;
import com.kashtech.jaas.domain.User;

public interface UserRepository extends MongoRepository<User, String>{

    public User findByUsername(String username);
}

DataSourceConfig

@Configuration
@EnableJpaRepositories("com.kashtech.jaas.repository")
@EnableTransactionManagement
public class DatasourceConfig implements EnvironmentAware {

private RelaxedPropertyResolver mongoDBResolver;

@Bean
public Mongo mongo() throws Exception {
    return new MongoClient(mongoDBResolver.getProperty("host", mongoDBResolver.getProperty("port")));
}

@Bean
public MongoTemplate mongoTemplate() throws Exception {

    try {
        log.info("##################### Configuring Mongo DataSource ####################");            
        log.info("Host : " + mongoDBResolver.getProperty("host"));
        log.info("Port : " + mongoDBResolver.getProperty("port"));
        log.info("Database : " + mongoDBResolver.getProperty("database"));
        log.info("#######################################################################");
    } catch (Exception e) {
        log.error("Database Connection Error ... Check the configurations.");
    }

    return new MongoTemplate(mongo(), mongoDBResolver.getProperty("database"));
}

Stacktrace

2017-04-28 19:19:56.551  INFO 7592 --- [           main] com.kashtech.JaasLoginModuleTests        : Starting JaasLoginModuleTests on Panther with PID 7592 (started by kashif in C:\Development\workspaces\jaas-system)
2017-04-28 19:19:56.551  INFO 7592 --- [           main] com.kashtech.JaasLoginModuleTests        : The following profiles are active: Dev
2017-04-28 19:19:56.578  INFO 7592 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1757cd72: startup date [Fri Apr 28 19:19:56 BST 2017]; root of context hierarchy
2017-04-28 19:19:56.905  INFO 7592 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2017-04-28 19:19:56.924  INFO 7592 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface com.kashtech.jaas.repository.mongodb.UserRepository.
2017-04-28 19:19:56.931  INFO 7592 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2017-04-28 19:19:56.982  INFO 7592 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'mongo' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=datasourceConfig; factoryMethodName=mongo; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/kashtech/jaas/config/DatasourceConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; factoryMethodName=mongo; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]]
2017-04-28 19:19:57.190  INFO 7592 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-04-28 19:19:57.359  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : ##################### Configuring DataSource #####################
2017-04-28 19:19:57.359  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : Driver class : com.mysql.jdbc.Driver
2017-04-28 19:19:57.359  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : Driver URL : jdbc:mysql://localhost/ebay-manager
2017-04-28 19:19:57.359  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : Driver username : root
2017-04-28 19:19:57.360  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : Driver password : admin
2017-04-28 19:19:57.480  INFO 7592 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-28 19:19:57.499  INFO 7592 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-04-28 19:19:57.573  INFO 7592 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2017-04-28 19:19:57.575  INFO 7592 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-04-28 19:19:57.576  INFO 7592 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-04-28 19:19:57.618  INFO 7592 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Fri Apr 28 19:19:57 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2017-04-28 19:19:58.159  INFO 7592 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-28 19:19:58.440  WARN 7592 --- [           main] o.h.b.i.SessionFactoryBuilderImpl        : Unrecognized hbm2ddl_auto value : none.  Supported values include create, create-drop, update, and validate.  Ignoring
2017-04-28 19:19:58.556  INFO 7592 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-04-28 19:19:58.575  INFO 7592 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-28 19:19:58.575  INFO 7592 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-04-28 19:19:58.585  INFO 7592 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-28 19:19:58.596  WARN 7592 --- [           main] o.h.b.i.SessionFactoryBuilderImpl        : Unrecognized hbm2ddl_auto value : none.  Supported values include create, create-drop, update, and validate.  Ignoring
2017-04-28 19:19:58.602  WARN 7592 --- [           main] o.h.j.i.EntityManagerFactoryRegistry     : HHH000436: Entity manager factory name (default) is already registered.  If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name'
2017-04-28 19:19:58.602  INFO 7592 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-04-28 19:19:58.646  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : ##################### Configuring Mongo DataSource ####################
2017-04-28 19:19:58.646  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : Host : 127.0.0.1
2017-04-28 19:19:58.646  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : Port : 27017
2017-04-28 19:19:58.646  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : Database : ebay-manager
2017-04-28 19:19:58.646  INFO 7592 --- [           main] c.kashtech.jaas.config.DatasourceConfig  : #######################################################################
2017-04-28 19:19:59.212  INFO 7592 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[127.0.0.1:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2017-04-28 19:19:59.212  INFO 7592 --- [           main] org.mongodb.driver.cluster               : Adding discovered server 127.0.0.1:27017 to client view of cluster
2017-04-28 19:19:59.309  INFO 7592 --- [127.0.0.1:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:18}] to 127.0.0.1:27017
2017-04-28 19:19:59.311  INFO 7592 --- [127.0.0.1:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 2]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, roundTripTimeNanos=613444}
2017-04-28 19:19:59.312  INFO 7592 --- [127.0.0.1:27017] org.mongodb.driver.cluster               : Discovered cluster type of STANDALONE
2017-04-28 19:19:59.453  INFO 7592 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:19}] to 127.0.0.1:27017
2017-04-28 19:19:59.915  INFO 7592 --- [           main] com.kashtech.JaasLoginModuleTests        : Started JaasLoginModuleTests in 3.67 seconds (JVM running for 4.403)
2017-04-28 19:20:00.035  INFO 7592 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@103f852 testClass = JaasLoginModuleTests, testInstance = com.kashtech.JaasLoginModuleTests@44a3ec6b, testMethod = testLogin@JaasLoginModuleTests, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@587c290d testClass = JaasLoginModuleTests, locations = '{}', classes = '{class com.kashtech.JaasSystemApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@14acaea5, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@59fa1d9b, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@77cd7a0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@60c8a093]; rollback [true]
2017-04-28 19:20:00.065  INFO 7592 --- [           main] com.kashtech.JaasLoginModuleTests        : Callback Handler invoked 
test
2017-04-28 19:20:00.068 ERROR 7592 --- [           main] com.kashtech.JaasLoginModuleTests        : Error whilst testing login : java.lang.NullPointerException
at com.kashtech.jaas.domain.JaasLoginModule.findUserFromDB(JaasLoginModule.java:307)
at com.kashtech.jaas.domain.JaasLoginModule.login(JaasLoginModule.java:146)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.security.auth.login.LoginContext.invoke(Unknown Source)
at javax.security.auth.login.LoginContext.access$000(Unknown Source)
at javax.security.auth.login.LoginContext$4.run(Unknown Source)
at javax.security.auth.login.LoginContext$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(Unknown Source)
at javax.security.auth.login.LoginContext.login(Unknown Source)
at com.kashtech.JaasLoginModuleTests.testLogin(JaasLoginModuleTests.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

2017-04-28 19:20:00.077  INFO 7592 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@103f852 testClass = JaasLoginModuleTests, testInstance = com.kashtech.JaasLoginModuleTests@44a3ec6b, testMethod = testLogin@JaasLoginModuleTests, testException = java.lang.NullPointerException, mergedContextConfiguration = [MergedContextConfiguration@587c290d testClass = JaasLoginModuleTests, locations = '{}', classes = '{class com.kashtech.JaasSystemApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@14acaea5, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@59fa1d9b, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@77cd7a0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2017-04-28 19:20:00.086  INFO 7592 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@1757cd72: startup date [Fri Apr 28 19:19:56 BST 2017]; root of context hierarchy
2017-04-28 19:20:00.089  INFO 7592 --- [       Thread-3] org.mongodb.driver.connection            : Closed connection [connectionId{localValue:2, serverValue:19}] to 127.0.0.1:27017 because the pool has been closed.
2017-04-28 19:20:00.091  INFO 7592 --- [       Thread-3] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

1 个答案:

答案 0 :(得分:0)

你正在调用新的哪个init是IoC容器之外的类,因此spring无法注入它。将课程自动装配到单元测试中。您的JaasLoginModule需要定义为Bean,组件,服务,然后自动连接到测试类。