cel*_*epo 5 java spring dependency-injection intellij-idea constructor-injection
我坚信将我的Spring Java字段注入[@Autowired]转换为构造函数注入(除其他原因外,以方便模拟单元测试)...
有没有可以用来自动完成Spring字段到构造函数注入转换的实用程序?
例如,IntelliJ IDEA有很多东西的生成快捷方式(即:为字段生成设置器和获取器);我希望有类似的东西...当手动进行繁琐的转换时,这特别有用,因为要转换的类已经有许多字段注入的字段。
是的,它现在已在 IntelliJ IDEA 中实现。
1) 将光标放在@Autowired注释之一上。
2)命中Alt+Enter。
3) 选择 Create constructor
Spring 团队建议:“始终在 bean 中使用基于构造函数的依赖注入。始终对强制依赖使用断言”。
字段注入/NullPointerException 示例:
Run Code Online (Sandbox Code Playgroud)class MyComponent { @Inject MyCollaborator collaborator; public void myBusinessMethod() { collaborator.doSomething(); // -> NullPointerException } }应该使用构造函数注入:
Run Code Online (Sandbox Code Playgroud)class MyComponent { private final MyCollaborator collaborator; @Inject public MyComponent(MyCollaborator collaborator) { Assert.notNull(collaborator, "MyCollaborator must not be null!"); this.collaborator = collaborator; } public void myBusinessMethod() { collaborator.doSomething(); // -> safe } }
没有什么开箱即用的。
我的做法是,我搜索并替换
@Autowired privateto
@Autowired private final。
然后有一个错误显示,说final fields没有初始化。
如果您执行自动完成(Alt+Enter),则它会询问您是否要创建构造函数,然后您可以选择字段并单击 Enter。
私人只是一个例子。它可以是任何修饰符。主要的事情是使字段最终,以便 Idea 因错误而哭泣,我们可以启动自动完成以生成所需的构造函数
| 归档时间: |
|
| 查看次数: |
2571 次 |
| 最近记录: |