Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuration Properties by @Autowired is null in Spring Boot

I have a properties class

@ConfigurationProperties(prefix = ShiroProperties.SHIRO_PREFIX)
public class ShiroProperties {
  public static final String SHIRO_PREFIX = "shiro";

  private String urlLogin;
  private String urlSuccessed;

and a Configuration class

@Configuration
@EnableConfigurationProperties({ ShiroProperties.class })
public class ShiroConfig implements ApplicationContextAware {

  ApplicationContext applicationContext;
  @Autowired
  private ShiroProperties shiroProperties ;

shiroProperties is null, but i can find it value in ShiroConfig used

applicationContext.getBean(ShiroProperties.class)

my Application class:

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

So weird, i can run success with similar code in other project, but this.

like image 362
Dean Avatar asked Feb 27 '17 11:02

Dean


People also ask

Why Autowired is getting null?

If the application starts and your field appears to be null it is generally due to one of the following issues: Using @Autowired on a static field. Omitted @Autowired on a field. Instance of bean not visible to Spring.

Can configuration class be Autowired?

The configuration classes themselves are registered as beans to the Spring container. That means, we can do whatever we do with a normal spring bean. For example we can use @Autowire to have Spring to perform DI in them.

Why is @autowired not working?

When @Autowired doesn't work. There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.

What is @configuration in Spring boot?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.


1 Answers

I met this same issue as @Dean said,I had done is put the LifecycleBeanPostProcessor bean is another configure class ,and configure other Shiro in another configuration class ,see below example:

@Configuration
public class ShiroLifecycleBeanPostProcessorConfig {

    /**
     * 
     * 
     * @return
     */
    @Bean(name = "lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

}

The main Shiro Configuration class:

@Configuration
@AutoConfigureAfter(value = ShiroLifecycleBeanPostProcessorConfig.class)
public class ShiroConfiguration {

    public static final String cacheFile = "encache.xml";
    private static final String active_cache_name = "activeSessionCache";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 
     * 
     * @throws UnknownHostException
     */
    @Bean(name = "shiroFilter")
    @ConditionalOnMissingBean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager)
            throws UnknownHostException {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        shiroFilterFactoryBean.setSecurityManager(securityManager);

        shiroFilterFactoryBean.setLoginUrl(ShiroSecurityUrls.LOGIN_PAGE);
        // shiroFilterFactoryBean.setSuccessUrl(ShiroSecurityUrls.LOGIN_SUCCESS_URL);
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");

        Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
        LogoutFilter logoutFilter = new LogoutFilter();
        logoutFilter.setRedirectUrl(ShiroSecurityUrls.LOGIN_PAGE);
        filters.put(DefaultFilter.logout.name(), logoutFilter);
        shiroFilterFactoryBean.setFilters(filters);

        Map<String, String> filterChainDefinitionManager = new LinkedHashMap<String, String>();

        filterChainDefinitionManager.put("/static/**", DefaultFilter.anon.name());
        filterChainDefinitionManager.put("/node_modules/**", DefaultFilter.anon.name());
        filterChainDefinitionManager.put("/pages/**", DefaultFilter.anon.name());

        filterChainDefinitionManager.put(ShiroSecurityUrls.LOGIN_PAGE, DefaultFilter.anon.name());
        filterChainDefinitionManager.put(ShiroSecurityUrls.LOGOUT_URL, DefaultFilter.logout.name());
        filterChainDefinitionManager.put(ShiroSecurityUrls.REGISTER_PROCESS_URL, DefaultFilter.anon.name());
        filterChainDefinitionManager.put("/**", DefaultFilter.user.name());

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionManager);

        return shiroFilterFactoryBean;
    }

    /**
     * 
     * 
     * @throws UnknownHostException
     */
    @Bean(name = "securityManager")
    @DependsOn(value = { "ehCacheManager", "rememberMeManager", "sessionManager", "credentialsMatcher" })
    public DefaultWebSecurityManager securityManager(EhCacheManager ehCacheManager, RememberMeManager rememberMeManager,
            SessionManager sessionManager, CredentialsMatcher credentialsMatcher) throws UnknownHostException {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 1. Cache Support
        securityManager.setCacheManager(ehCacheManager);
        // 2. Session Support,inject the cacheManager from securitymanager
        securityManager.setSessionManager(sessionManager);
        // 3. Rememberme Support
        securityManager.setRememberMeManager(rememberMeManager);

        // 4. JDBC,LDAP Realm implements
        Collection<Realm> authorizingRealms = Lists.newArrayList(shiroDatabaseRealm(credentialsMatcher),
                shiroActiveDirectoryRealm(credentialsMatcher));
        securityManager.setRealms(authorizingRealms); // inject the cacheManager
                                                        // from securitymanager
        if (securityManager.getAuthenticator() instanceof ModularRealmAuthenticator) {
            ModularRealmAuthenticator modularRealmAuthenticator = (ModularRealmAuthenticator) securityManager
                    .getAuthenticator();
            modularRealmAuthenticator.setAuthenticationStrategy(new FirstSuccessfulStrategy());
        }

        return securityManager;
    }
}

Hope this code helps you ,thanks.

like image 185
Alter Hu Avatar answered Oct 05 '22 23:10

Alter Hu