好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringBoot之Java配置的实现

java配置也是spring4.0推荐的配置方式,完全可以取代xml的配置方式,也是springboot推荐的方式。

java配置是通过@configuation和@bean来实现的:

  1、@configuation注解,说明此类是配置类,相当于spring的xml方式

  2、@bean注解,注解在方法上,当前方法返回的是一个bean

eg:

此类没有使用@service等注解方式

?

1

2

3

4

5

6

7

package com.wisely.heighlight_spring4.ch1.javaconfig;

 

public class functionservice {

   public string sayhello(string world) {

     return "hello " + world + "!" ;

   }

}

此类没有使用@service注解lei,也没有使用@autowire注入bean

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

package com.wisely.heighlight_spring4.ch1.javaconfig;

 

public class usefunctionservice {

  

   functionservice functionservice;

 

   public void setfunctionservice(functionservice functionservice) {

     this .functionservice = functionservice;

   }

  

   public string sayhello(string world) {

     return functionservice.sayhello(world);

   }

}

1、使用@configuation注解说明此类是一个配置类

2、使用@bean注解的方式注解在方法上,返回一个实体bean,bean的名称是方法名。

3、注入functionservice的bean的时候,可以直接使用functionservice方法。

4、注解将functionservice作为参数直接传入usefunctionservice。在spring容器中,只要在容器中存在一个bean,就可已在另一个bean的声明方法的参数中直接使用。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

package com.wisely.heighlight_spring4.ch1.javaconfig;

 

import org.springframework.context.annotation.bean;

import org.springframework.context.annotation.configuration;

 

@configuration

public class javaconfig {

   @bean

   public functionservice functionservice() {

     return new functionservice();

   }

  

   @bean

   public usefunctionservice usefunctionservice() {

     usefunctionservice usefunctionservice = new usefunctionservice();

     usefunctionservice.setfunctionservice(functionservice());

     return usefunctionservice;

   }

  

   @bean

   public usefunctionservice usefunctionservice(functionservice functionservice) {

     usefunctionservice usefunctionservice = new usefunctionservice();

     usefunctionservice.setfunctionservice(functionservice);

     return usefunctionservice;

   }

}

测试类:

?

1

2

3

4

5

6

7

8

9

10

11

12

package com.wisely.heighlight_spring4.ch1.javaconfig;

 

import org.springframework.context.annotation.annotationconfigapplicationcontext;

 

public class main {

   public static void main(string[] args) {

     annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(javaconfig. class );

     usefunctionservice usefunctionservice = context.getbean(usefunctionservice. class );

     system.out.println(usefunctionservice.sayhello( "java config" ));

     context.close();

   }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://www.cnblogs.com/JohnEricCheng/p/8621981.html

查看更多关于SpringBoot之Java配置的实现的详细内容...

  阅读:11次