java-依赖注入到Spring非托管bean中
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-依赖注入到Spring非托管bean中,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2575字,纯文字阅读大概需要4分钟。
内容图文
![java-依赖注入到Spring非托管bean中](/upload/InfoBanner/zyjiaocheng/681/d3e0486a5f9d4d46a93d67f7867f7a6b.jpg)
我有一个非托管的JPA域类.通过new运算符将其实例化.
UserAccount account = new UserAccount();
userRepository.save(account)
在我的UserAccount类中,我有一个beforeSave()方法,该方法依赖于我的SecurityService来对密码进行哈希编码.
我的问题是“如何获得Spring DI将安全服务注入我的实体?”.似乎我需要AspectJ和LoadTimeWeaving.我已经尝试过使用数组进行配置,但是似乎无法使它们中的任何一个起作用.尝试在注入的对象上调用方法时,总是会收到NullPointerException.
UserAccount.java(这是JPA实体)
@Entity
@Repository
@Configurable(autowire = Autowire.BY_TYPE)
public class UserAccount implements Serializable {
@Transient
@Autowired
SecurityService securityService;
private String passwordHash;
@Transient
private String password;
public UserAccount() {
super();
}
@PrePersist
public void beforeSave() {
if (password != null) {
// NullPointerException Here!!!
passwordHash = securityService.hashPassword(password);
}
}
}
试图表明跳动使用AspectJ:
NitroApp.java(主类)
@SpringBootApplication
@EnableTransactionManagement
@EnableSpringConfigured
@PropertySources(value = {@PropertySource("classpath:application.properties")})
public class NitroApp extends SpringBootServletInitializer {
public static void main (String[] args) {
SpringApplication.run(NitroApp.class);
}
}
build.gradle(配置)
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:1.2.2.RELEASE"
classpath "org.springframework:springloaded:1.2.2.RELEASE"
classpath "org.springframework:spring-aspects:4.1.6.RELEASE"
}
}
apply plugin: 'java'
apply plugin: 'aspectj'
apply plugin: 'application'
apply plugin: 'idea'
apply plugin: 'spring-boot'
repositories {
jcenter()
mavenLocal()
mavenCentral()
}
mainClassName = 'com.noxgroup.nitro.NitroApp'
applicationName = "Nitro"
idea {
module {
inheritOutputDirs = false
outputDir = file("$buildDir/classes/main/")
}
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("net.sourceforge.nekohtml:nekohtml:1.9.15")
compile("commons-codec:commons-codec:1.9")
compile("org.postgresql:postgresql:9.4-1201-jdbc41")
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
解决方法:
您可以在用于实例化UserAccount的类中注入Spring applicationContext.
@Autowired
private ApplicationContext applicationContext;
然后,通过以下方式创建UserAccount bean:
UserAccount userAccount = applicationContext.getBean(UserAccount.class);
这样,您可以在UserAccount类中注入所需的依赖项.
内容总结
以上是互联网集市为您收集整理的java-依赖注入到Spring非托管bean中全部内容,希望文章能够帮你解决java-依赖注入到Spring非托管bean中所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。