Spring Foundation (3)---spring base configuration

Source: Internet
Author: User

Spring Base Configuration

The Sprin framework itself has four principles:

    • Use Pojo for lightweight and minimal intrusive development.
    • Loose coupling is achieved through dependency injection and interface-based programming.
    • Use AOP to implement the default custom for declarative programming.
    • Use AOP and templates (template) to reduce the modularity of code.

The design and implementation of all the functions of Spring is based on this four principles.

1, Dependency injection 1.1, theory

We often say that control inversion (IOC) and Dependency Injection (DI) are two equivalent concepts in a spring environment, and control reversals are implemented through dependency injection. The so-called dependency injection refers to the container in charge of creating objects and maintaining the dependencies between objects, rather than through the object itself responsible for their own creation and resolution of their own dependencies.
The main purpose of dependency injection is to understand the decoupling and embody a concept of "combination". If you want your class to have a function of a class if you inherit a parent class, the subclass and parent class will be coupled if the other class is combined to reduce the coupling.
The spring IOC container is responsible for creating beans and injecting the bean of the functional class into the bean you need, and spring can be configured with XML, annotations, and Java configuration to create and access the bean, and the inability is that configuration, which is called the configuration metadata, Also called descriptive data, meaning that the data itself does not have any ability to execute, only through the external code to parse the metadata to make some interesting data.

To declare a bean's annotations:
    • @Component component, there is no clear role.
    • @Controller used in the presentation layer (MVC→SPRINGMVC).
    • @Service used at the Business Logic Layer (service layer).
    • @Repository used in the Data Access Layer (DAO layer).

      Injected bean annotations, generally common
    • @Autowired: Annotations provided by spring.
    • @Inject: Annotations provided by JSR-330.
    • @Resource: Annotations provided by JSR-250.

1.2. Example

1) write the bean for the function class.

package com.wisely.highlight_spring4.ch1.di;import org.springframework.stereotype.Service;@Service //使用@Service注解声明当前FunctionService类是Spring管理的一个Bean。其中,使用@Controller、@Service、@Repository和@Controller是等效的,可根据当前Bean在哪一层使用。public class FunctionService {    public String sayHello(String word){        return "Hello " + word +" !";     }}

2) Use the bean of the function class.

package com.wisely.highlight_spring4.ch1.di;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Service //声明当前类是Spring管理的一个Beanpublic class UseFunctionService {    @Autowired //将FunctionService的实体Bean注入到UseFunctionService中    FunctionService functionService;        public String SayHello(String word){        return functionService.sayHello(word);    }}

3) Configuration Class

package com.wisely.highlight_spring4.ch1.di;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration //声明当前类是一个配置类@ComponentScan("com.wisely.highlight_spring4.ch1.di") //自动扫描包名下所有的@Service、@Component、@Repository、@Controller的类并注册为Beanpublic class DiConfig {}

4) Run

package com.wisely.highlight_spring4.ch1.di;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {    public static void main(String[] args) {        //使用AnnotationConfigApplicationContext作为容器,接受一个配置类作为参数拿到上下文对象         AnnotationConfigApplicationContext context =                    new AnnotationConfigApplicationContext(DiConfig.class);         //获得Bean         UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);                  System.out.println(useFunctionService.SayHello("world"));//Hello world !                  context.close();    }}
2. Java Configuration 2.1, theory

The Java configuration is the recommended configuration for spring4.x, which can completely replace the XML configuration, and the Java configuration is also the Springboot recommended configuration method.
The Java configuration is implemented primarily through @configuration and @bean.

    • @Configuration declares that the current class is a configuration class, equivalent to an XML file that is configured in spring.
    • @Bean annotations on a method, declares that the return value of the current method is a bean.
      If you replace the XML configuration with a Java configuration, our main principle is that the global configuration is configured with Java configuration (such as database-related configuration, MVC-related configuration), and the business bean configuration uses the annotation configuration (@Service, @Component, @Repository, @ Controller).
2.2. Example

1) write the bean of the function class

package com.wisely.highlight_spring4.ch1.javaconfig;//这里没有用@Service注解声明Beanpublic class FunctionService {        public String sayHello(String word){        return "Hello " + word +" !";     }}

2) Beans using the function class

package com.wisely.highlight_spring4.ch1.javaconfig;//此处没有用@Service声明Beanpublic class UseFunctionService {    //此处也没有用@AutoWired注解注入    FunctionService functionService;        public void setFunctionService(FunctionService functionService) {        this.functionService = functionService;    }        public String SayHello(String word){        return functionService.sayHello(word);    }}

3) Configuration Class

Package Com.wisely.highlight_spring4.ch1.javaconfig;import Org.springframework.context.annotation.bean;import org.springframework.context.annotation.Configuration; @Configuration//declares that this is a configuration class, which means that there are 0 or more @bean annotations in this class, There is no @componentscan package to scan the annotations public class Javaconfig {@Bean//declares that the current method returns a Bean,bean name is the method name public Functionservice Functi    Onservice () {return new Functionservice (); } @Bean Public Usefunctionservice Usefunctionservice () {Usefunctionservice usefunctionservice = new Usefu        Nctionservice (); Usefunctionservice.setfunctionservice (Functionservice ());        Functionservice () is called directly when the bean is injected into the functionservice.            return usefunctionservice; }//@Bean//Another way of injection: directly to the Functionservice as a parameter to Usefunctionservice (), which is also the spring container, as long as the container exists in the Bean, it can be in// Another bean is injected as a parameter in the declaration method. Public Usefunctionservice Usefunctionservice (Functionservice functionservice) {//4//Usefunctionservice useFunctio Nservice = new Usefunctionservice ();//USEFUNCTIONSERVICE.SEtfunctionservice (Functionservice);//Return usefunctionservice;//}} 

4) Run

package com.wisely.highlight_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"));//Hello java config!                  context.close();            }}
3, AOP3.1, theory

AOP: aspect-oriented programming, relative to OOP object-oriented programming.
The existence of spring's AOP is mainly for the understanding of decoupling. AOP can allow a group of classes to share common behaviors that can be implemented in OOP only with an integration class or implementation interface, which can be an enhancement of the coupling of the code, and the integration can only be single-inherited, hindering the addition of more behaviors on a set of classes, mainly to compensate for the shortcomings of OOP.
Spring supports annotated cut-off programming for ASPECTJ.

    1. Use @asopect to declare a slice.
    2. Using @after, @Before, @Around definition (advice), you can directly use interception rules (pointcuts) as parameters.
    3. The interception rules for @after, @Before, @Around parameters are tangent points (ponintcut), in order to make the pointcut reuse, you can specifically define the interception rules with @ponitcut, and then call them in @after, @Before, @Around parameters.
      4. Each intercepted place that meets the criteria is referred to as a connection point (Joinponit).
3.2. Example

1) Add spring AOP Support and AspectJ dependency in Pom.xml

       <!-- spring aop支持 -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-aop</artifactId>            <version>${spring-framework.version}</version>        </dependency>        <!-- aspectj支持 -->        <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjrt</artifactId>            <version>1.8.6</version>        </dependency>        <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjweaver</artifactId>            <version>1.8.5</version>        </dependency>

2) Write the Interception rule annotations (Customize an annotation)

Package Com.wisely.highlight_spring4.ch1.aop;import Java.lang.annotation.documented;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;//@ Target illustrates the range of objects that annotation modifies: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, constructor methods, member variables, enumeration values), Method parameters and local variables (such as loop variables, catch parameters). Target can be more clearly decorated by using target in the declaration of the annotation type. Function: Used to describe the use of annotations (i.e., where the annotations described can be used)//values (ElementType) are://1.CONSTRUCTOR: Used to describe the constructor//2.FIELD: Used to describe a domain//3.local_variable: Used to describe a local variable//4.METHOD: For Description method//5.PACKAGE: For Description Package//6.PARA METER: Used to describe parameters//7.TYPE: Used to describe classes, interfaces (including annotation types) or enum declarations//@Retention defines how long the annotation is retained: Some annotation appear only in the source code and are discarded by the compiler; Others are compiled in the class file, and the annotation compiled in the class file may be ignored by the virtual machine, while others will be read when class is loaded (note that it does not affect class execution, Because the annotation is separated from the class in use). Using this meta-annotation can limit the "life cycle" of annotation. Function: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., what is the description of the annotation is valid)//value (RetentioNpoicy) has://1.SOURCE: Valid in the source file (that is, the source file is reserved)//2.CLASS: Valid in the class file (that is, class reserved)//3.RUNTIME: Valid at run time (that is, run-time retention) @Target (Elementtyp E.method) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Action {String name ();}

3) write the intercepted class using annotations

package com.wisely.highlight_spring4.ch1.aop;import org.springframework.stereotype.Service;@Servicepublic class DemoAnnotationService {    @Action(name="注解式拦截的add操作")    public void add(){}    }

4) Write a class that is intercepted using method rules

package com.wisely.highlight_spring4.ch1.aop;import org.springframework.stereotype.Service;@Servicepublic class DemoMethodService {    public void add(){}}

5) Writing Facets

Package Com.wisely.highlight_spring4.ch1.aop;import Java.lang.reflect.method;import Org.aspectj.lang.JoinPoint; Import Org.aspectj.lang.annotation.after;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.before;import Org.aspectj.lang.annotation.pointcut;import Org.aspectj.lang.reflect.methodsignature;import org.springframework.stereotype.Component; @Aspect// Declares a slice @component//makes this facet Beanpublic class Logaspect {@Pointcut ("@annotation (com.wisely.highlight_spring          4.ch1.aop.action)//Declaration tangent public void Annotationpointcut () {};  @After ("Annotationpointcut ()")//Post notification public void after (Joinpoint joinpoint) {methodsignature signature            = (methodsignature) joinpoint.getsignature ();            Method method = Signature.getmethod ();             Action action = method.getannotation (Action.class); System.out.println ("Annotated interception" + action.name ()); Use reflection to get the attributes on the annotation, and then you can do the log-related actions} @Before ("Execution (* Com.wisely.highlight_spring4.ch1.aop.demomethodservice.* (..)) ") The pre-notification public void before (Joinpoint joinpoint) {methodsignature signature = (methodsignature) joinpoint.            Getsignature ();            Method method = Signature.getmethod ();        System.out.println ("Method rule-blocking," +method.getname ()); }}

6) Configuration Class

package com.wisely.highlight_spring4.ch1.aop;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.EnableAspectJAutoProxy;@Configuration@ComponentScan("com.wisely.highlight_spring4.ch1.aop")@EnableAspectJAutoProxy //开启Spring对AspectJ支持public class AopConfig {}

7) Run

package com.wisely.highlight_spring4.ch1.aop;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {    public static void main(String[] args) {         AnnotationConfigApplicationContext context =                    new AnnotationConfigApplicationContext(AopConfig.class);                  DemoAnnotationService demoAnnotationService = context.getBean(DemoAnnotationService.class);                  DemoMethodService demoMethodService = context.getBean(DemoMethodService.class);                  demoAnnotationService.add();                  demoMethodService.add();                  context.close();    }}

Spring Foundation (3)---spring base configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.