Grails3在utils中注入bean

Grails3在utils中注入bean

grails-app/conf/application.yml中配置用户基本信息

  1. user:
  2. pserson-name: 张三
  3. age: 20
  4. sex:

grails-app/utils下面新建一个JavaBean

注意

  • 这里的包名最好跟init/Application.groovy下面的保持一致,比如:Application.groovy是在com.demo下面,那么这个JavaBean也必须是在com.demo下面,例:com.demo.config
  1. package com.demo.config;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. @ConfigurationProperties(prefix = "user")
  6. public class UserConfig {
  7. private String psersonName;
  8. private Integer age;
  9. private char sex;
  10. public String getPsersonName() {
  11. return psersonName;
  12. }
  13. public void setPsersonName(String psersonName) {
  14. this.psersonName = psersonName;
  15. }
  16. public Integer getAge() {
  17. return age;
  18. }
  19. public void setAge(Integer age) {
  20. this.age = age;
  21. }
  22. public char getSex() {
  23. return sex;
  24. }
  25. public void setSex(char sex) {
  26. this.sex = sex;
  27. }
  28. @Override
  29. public String toString() {
  30. return "UserConfig{" +
  31. "psersonName='" + psersonName + '\'' +
  32. ", age='" + age + '\'' +
  33. ", sex=" + sex +
  34. '}';
  35. }
  36. }

新建UserUtils

  1. package com.demo.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class UserUtils {
  6. @Autowired
  7. private UserConfig config;
  8. public String get() {
  9. System.out.println(config);
  10. return "用户姓名为:"+config.getPsersonName();
  11. }
  12. }

别忘了在主配置类Application上面加上@ComponetScan启用组件扫描

  1. @ComponentScan
  2. class Application extends GrailsAutoConfiguration {
  3. static void main(String[] args) {
  4. GrailsApp.run(Application, args)
  5. }
  6. }

通过@Integration启用集成测试

  1. package com.system
  2. import grails.test.mixin.TestFor
  3. import grails.test.mixin.integration.Integration
  4. import org.springframework.beans.factory.annotation.Autowired
  5. import org.springframework.boot.test.IntegrationTest
  6. import spock.lang.Specification
  7. import websocket.UserUtils
  8. /**
  9. * See the API for {@link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
  10. */
  11. @Integration
  12. class TestControllerSpec extends Specification {
  13. @Autowired
  14. private UserUtils util
  15. def setup() {
  16. }
  17. def cleanup() {
  18. }
  19. void "user test" () {
  20. expect: 'execlute'
  21. util.get()
  22. }
  23. void "test something"() {
  24. expect:"fix me"
  25. true == false
  26. }
  27. }

控制台打印

  1. Grails application running at http://localhost:8080 in environment: development
  2. UserConfig{psersonName='张三', age='20', sex=男}

0
1
0

添加评论

正在回复:
取消
0
0
1
0