- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
<分区>
SOLVED
最近我在尝试开发 Spring MVC 应用程序时遇到了问题。主要问题是我不知道为什么 @Autowired 注释不能正常工作,这可能是因为我有问题。我将在这里发布我的代码,以便您可以帮助我解决我的问题!非常感谢你们:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>HelloWorld Application</display-name>
<description>
This is a simple web application with a source code organization
based on the recommendations of the Application Developer's Guide.
</description>
<servlet>
<servlet-name>webDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webDispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.agrichem.server" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="securityDao"
class="com.agrichem.server.model.repositories.impl.SecurityDaoImpl">
</bean>
</beans>
webDispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.agrichem.server" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- <import resource="spring-security-web.xml"/> -->
</beans>
SecurityDao.java
public interface SecurityDao {
public boolean validateUser(User user);
public User authenticateUser(User user);
public User getUser (User user);
}
SecurityDaoImpl.java
@Repository("securityDao")
public class SecurityDaoImpl extends HibernateDao implements SecurityDao {
public SecurityDaoImpl() {
super();
}
@Override
public boolean validateUser(User user) {
Query query = openSession()
.createQuery(
"from User u where u.login = :login and u.password = :password");
query.setParameter("login", user.getLogin());
query.setParameter("password", user.getPassword());
return (query.list().size() > 0) ? true : false;
}
@Override
public User authenticateUser(User user) {
Query query = openSession()
.createQuery(
"from User u where u.login = :login and u.password = :password");
query.setParameter("login", user.getLogin());
query.setParameter("password", user.getPassword());
return (User) query.uniqueResult();
}
@Override
public User getUser(User user) {
Query query = openSession().createQuery(
"from User u where u.login = :login");
query.setParameter("login", user.getLogin());
return (User) query.uniqueResult();
}
}
WebSecurityConfig.java
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(new CustomUserDetailsService());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/home/logout.do").permitAll()
.anyRequest().authenticated().and().formLogin()
.loginPage("/home/login.do").permitAll()
.failureUrl("/home/accessdenied.do").permitAll();
}
}
CustomUserDetailsService.java
@Configurable
@Transactional
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
@Qualifier("securityDao")
private SecurityDao securityDAO;
@Override
public UserDetails loadUserByUsername(String arg0)
throws UsernameNotFoundException {
com.agrichem.server.model.security.User user = securityDAO
.getUser(new com.agrichem.server.model.security.User(arg0, ""));
User userDetails = new User(user.getLogin(), user.getPassword(),
getGrantedAuthorities(user.getRoles()));
return userDetails;
}
public static List<GrantedAuthority> getGrantedAuthorities(Set<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
public SecurityDao getSecurityDAO() {
return securityDAO;
}
public void setSecurityDAO(SecurityDao securityDAO) {
this.securityDAO = securityDAO;
}
}
此时,当我尝试登录应用程序并检查 Dao 以访问数据库时,我得到的“securityDao”属性为空。完全在 CustomUserDetailsService 中的以下行中:com.agrichem.server.model.security.User user = securityDAO.getUser(new com.agrichem.server.model.security.User(arg0, ""));很明显,我遇到了 NullPointerException。
org.springframework.security.authentication.InternalAuthenticationServiceException
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at com.agrichem.server.services.security.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:35)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
... 36 more
解决方法:
找到了!问题是在 WebSecurityConfig 中我做了以下事情:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(**new CustomUserDetailsService()**);
}
然后 CustemUserDetailsService 的新实例脱离了 Spring Control。
为了解决这个问题,我在 CustomUserDetailsService 中添加了一个构造函数:
private SecurityDao securityDAO;
public CustomUserDetailsService(SecurityDao securityDAO) {
super();
this.securityDAO = securityDAO;
}
我以这种方式修改了 WebSecurityConfig:
@Autowired
private SecurityDao securityDao;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(new CustomUserDetailsService(securityDao));
}
无论如何感谢您的帮助!
这更像是一个最佳实践类型的问题。 我听过很多次: a) 在 Spring 中 Autowiring 时,最佳做法是 Autowiring 接口(interface)“而不是”实现。 和.. b) 我还
我正在查看工作区中的一些旧示例。我看不出怎么样由于没有 @Autowired, Autowiring 完成。 Spring boot + facebook 默认配置。 @Controller @Req
事实似乎并非如此。我曾经认为 XML 配置是为了覆盖注释。但是当我在XML配置中设置autowire =“no”时,bean的@Autowired注释属性仍然有效。我不再确定 XML autowire
为什么需要 Autowiring ? Autowiring 概念的解释是什么?@autowired Spring Framework 中的注释. 最佳答案 不需要 Autowiring ,只是方便。
来自this Spring documentation我知道当我使用@Bean时,默认值已经相当于: @Bean(autowire = Autowire.NO) (Default) No autowi
遇到了一个奇怪的要求。我需要将唯一的错误 ID 附加到 log4j 消息并将该消息 ID 返回给接口(interface)。所以,我虽然让我们创建一个 spring 服务,就像这样 public cl
这个问题已经有答案了: @Autowire failing with @Repository (3 个回答) 已关闭 4 年前。 我有一个类“ReportEverythingForm”,它拒绝通过自动
我是 Spring 的新手。我正面临 Spring-Boot 的问题。我正在尝试将一个字段从外部配置文件 Autowiring 到一个 Autowiring 的 bean 中。我有以下类(class)
我有一个带有存储库的 Spring Boot 应用程序。 我还使用@Service并扩展其中的存储库。 当我尝试 @Autowired 我拥有的服务时: Caused by: org.springfr
我有一个接口(interface)C,想要访问另外两个类中的getClassName()。访问 a.getClassName() 时,method1() 中出现异常。 public interface
我遇到了一个奇怪的问题,其中注入(inject)了 @Autowire 的 Component 在一个类中可用,但在另一个类中不可用。 我在Account和Agreement类的属性network中使
考虑以下示例代码: public class SmallCar { private CarEngine carEngine; @Autowired public SmallCa
autowire = "no"和 autowire = "default"有什么区别?如果它们相同,那么为什么我们有这 2 个选项。 最佳答案 Beans The default is "defaul
我已将项目更改为使用注释而不是 xml 文件,但这会增加应用程序部署时间。现在我正在寻找减少它的方法。 按类型 Autowiring 和按名称 Autowiring 之间有性能差异吗? 热烈欢迎任何其
我有一个与 Web 插件一起使用的 spring boot 应用程序。 在一节课中我有: package com.test.company @Component @RestController pub
我有一个可以执行某些操作的系统。该系统使用以下方法为每个对象创建一个单独的线程: stp.scheduleWithFixedDelay((EditSite) ctx.getBean("EditSite
我正在尝试自动连接存储库,但它无法工作。我已经为此苦苦挣扎了一个星期,但我似乎无法弄清楚。有趣的是,当我注释掉人员存储库的 Autowiring 时,程序可以正常工作并正确编译,但是一旦我尝试 Aut
意味着如果具有所需类型的 bean 不超过 1 个,bean 的所有字段将自动注入(inject)依赖项。 问题是当使用注解时它是如何工作的,它到底能不能工作。 我的测试表明即使我使用 @Resou
我有一个 Autowiring 其他 bean 的组件: @Component public class MyComponent { @Autowired private Enviro
这是我的类代码,其中有 @Autowired 字段: 测试A @ContextConfiguration("classpath:spring.xml") public abstract class T
我是一名优秀的程序员,十分优秀!