sách gpt4 ai đã đi

Cách chuyển đổi cấu hình xml spring security hibernate sang cấu hình java bằng Spring-Security 3 và Hibernate 4

In lại 作者:行者123 更新时间:2023-11-30 09:11:17 28 4
mua khóa gpt4 Nike

我刚刚了解了 spring security 并想使用 java hibernate 配置连接到数据库,但我发现的示例或教程很少。我通过使用 xml 配置找到了更多。我在这里使用 Spring 4.0.2、Spring-Security 3.2.0 和 Hibernate 4.3.2

我的问题是:下面的xml怎么转成java配置?






CustomUserDetailsService.java 所在的位置

package com.whatever.svtest.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.whatever.svtest.dao.UserDao;

@Dịch vụ
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {

@Autowired
private UserDao userDao;

@Ghi đè
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

com.whatever.svtest.model.User domainUser = userDao.getByUsername(username);

if (domainUser == null) {
throw new UsernameNotFoundException("user not found");
}

List authorities = new ArrayList();
authorities.add(new SimpleGrantedAuthority("USER"));

return new User(username, domainUser.getPassword(), true, true, true, true, authorities);
}

}

在 SecurityConfig.java 上,我使用 spring 创建的默认登录表单。我想自己弄清楚如何将 xml 配置转换为 java 配置。

package com.whatever.svtest.init;

nhập org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import com.whatever.svtest.service.impl.UserServiceImpl;

@Cấu hình
@EnableWebSecurity
lớp công khai SecurityConfiguration mở rộng WebSecurityConfigurerAdapter {

@Ghi đè
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.userDetailsService(new UserServiceImpl()).passwordEncoder(NoOpPasswordEncoder.getInstance());

}

}

然后我像这样将 SecurityConfiguration.java 放在 Initializer.java 上

package com.whatever.svtest.init;

import javax.servlet.Filter;

import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Ghi đè
protected Class[] getRootConfigClasses() {
// return null;
return new Class[] { SecurityConfiguration.class };
}

@Ghi đè
protected Class[] getServletConfigClasses() {
return new Class[] { WebAppConfig.class };
}

@Ghi đè
protected String[] getServletMappings() {
return new String[] { "/" };
}

@Ghi đè
protected Filter[] getServletFilters() {
return new Filter[] { new DelegatingFilterProxy("springSecurityFilterChain") };
}

}

WebAppConfig.java

package com.whatever.svtest.init;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
nhập org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
nhập org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Cấu hình
@EnableWebMvc
@Import({ DatabaseConfig.class })
@ComponentScan(basePackages = { "com.whatever.svtest.controller" })
@PropertySource({ "classpath:persistence-mysql.properties" })
public class WebAppConfig extends WebMvcConfigurerAdapter {

@Tài nguyên
private Environment env;

@Ghi đè
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
}

@Đậu
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
source.setUseCodeAsDefaultMessage(true);
return source;
}

@Đậu
public ViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}

}

当我运行我的网络应用程序时,我得到了这个。 (我把图片放在这里 http://i.stack.imgur.com/Mssrc.jpg )

而且我还(在某处)阅读了有关创建 AuthenticationProvider.java 的自定义实现的内容,但我不知道将此代码放在哪里..

package com.whatever.svtest.init;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import com.whatever.svtest.dao.UserDao;
import com.whatever.svtest.model.User;

public class MyAuthProvider implements AuthenticationProvider {

@Autowired
private UserDao userDao;

@Ghi đè
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
User user = userDao.getByUsername(name);
authentication.setAuthenticated(user != null && password.equals(user.getPassword()));
return authentication;
}

@Ghi đè
public boolean supports(Class authentication) {

return (MyAuthProvider.class.isAssignableFrom(authentication));
}

}

1 Câu trả lời

配置不一致?

您发布的配置对我来说不太有意义。具体如下:

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new UserServiceImpl()).passwordEncoder(NoOpPasswordEncoder.getInstance());
}

一个解决方案

您似乎没有定义 UserServiceImpl,但您已经定义了 CustomUserDetailsService(这可能是应该传入的参数。但是,为了 Autowiring 一个 bean,您需要将其创建为一个 bean。所以你应该这样改变你的配置:

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(uds());
}

@Đậu
public CustomUserDetailsService uds() {
return new CustomUserDetailsService();
}

通过将 CustomUserDetailsService 作为 @Bean 返回,您可以确保 Spring 正确地 Autowiring 它。

一些附加说明:

  • 您不需要自定义 AuthenticationProvider。这是因为您使用用户名/密码进行身份验证,所以 UserDetailsService 没问题。如果您想使用用户名/密码以外的其他内容进行身份验证,您可以创建自定义 AuthenticationProvider
  • 无需指定空操作密码编码器,因为这是默认设置。

改进 CustomUserDetailsService

要指出当前实现的一件事是,虽然您可以直接使用@Autowire 字段,但它更容易出错,因此您可能应该更改 CustomUserDetailsService 以具有允许注入(inject) UserDao 的构造函数。这也使单元测试更容易(因此您不需要使用反射来设置 UserDao)。因此,您会将 CustomUserDetailsService 更新为:

@Dịch vụ
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {

private UserDao userDao;

@Autowired
public CustomUserDetailsService(UserDao userDao) {
this.userDao = userDao;
}

那么你的配置可以是这样的:

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(uds());
}

@Autowired
private UserDao userDao;

@Đậu
public CustomUserDetailsService uds() {
return new CustomUserDetailsService(userDao);
}

根据新错误更新

您还需要确保您的 UserDao 被拾取为 Bean。例如:

@Đậu
public UserDao userDao() {
return new UserDao(...);
}

注意:确保您正确初始化了 UserDao(即确保它的所有依赖项都已初始化。如果您在 UserDao 上使用 Autowired,请确保这些依赖项也是 @Đậu.

关于java - 如何使用 Spring-Security 3 和 Hibernate 4 将 spring security xml 配置 hibernate 转换为 java 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22176693/

28 4 0
Bài viết được đề xuất: python - TensorFlow 对于简单网络表现不佳吗?
Bài viết được đề xuất: machine-learning - 使用预制字典表示 SVM 特征向量进行文本分类
Bài viết được đề xuất: java - 无状态 session bean 事务
Bài viết được đề xuất: python - 在Python中绘制音频频谱图
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com