002-spring4 Quick Start "container assembly"

Source: Internet
Author: User

I. Project construction 1, Project creation

Eclipse→project Explorer→new→project→maven Project

Default configuration to create a project

2. Spring Configuration
        <Dependency>            <groupId>Org.springframework</groupId>            <Artifactid>Spring-context</Artifactid>            <version>4.3.13.RELEASE</version>        </Dependency>
View Code3. Configuration Project Compilation target version
    <Properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <Maven.compiler.source>1.8</Maven.compiler.source>        <Maven.compiler.target>1.8</Maven.compiler.target>    </Properties>
View Code

Right-click on the project to →maven→update project

Ii. annotation-based development bean,bean creating and assembling 1, adding configuration classes, creating beans

Method One, create a bean

Add annotations @configuration, @Bean, @Scope

@Configuration  Public class myconfig {    @Bean (name= "Mybean")    @Scope ("prototype")    public  Mybean Createmybean () {        returnnew  Mybean ();}    }
View Code

Method Two, create using Factorybean, lambda mode

 Public classRunnablefactorybeanImplementsFactorybean<runnable>{@Override PublicRunnable GetObject ()throwsException {return(){}; } @Override PublicClass<?>Getobjecttype () {returnRunnable.class; } @Override Public BooleanIssingleton () {return true; }}
View Code

If you define a Jeep, tell the factory class to change to

 Public classRunnablefactorybeanImplementsFactorybean<jeep>{@Override PublicJeep GetObject ()throwsException {return NewJeep (); } @Override PublicClass<?>Getobjecttype () {returnJeep.class; } @Override Public BooleanIssingleton () {return true; }}
View Code

can be used.

Method Three, need parameters, default will be obtained, automatic injection

Create a class Car

Create a factory

 Public class carfactory {    public  Car Create () {        returnnew  Car ();    }}
View Code

Add in config

    @Bean    public  carfactory createcarfactory () {        returnnew carfactory ();    }        @Bean    public  Car createcar (Carfactory factory) {        return  Factory.create ();    }
View Code

Use: System.out.println (Annotationconfigapplicationcontext.getbean (Car.class));//Name Acquisition

2. Add configuration at the method entrance

Method One, configure one or more specified types

New Annotationconfigapplicationcontext (myconfig. class);

Method Two, configure the specified scanned package

Annotationconfigapplicationcontext context = new Annotationconfigapplicationcontext ("com.lhx.spring.spring");

Method Three, configure the specified package, and exclude

@ComponentScan (basepackages= "com.lhx.spring.spring", [email protected] (Type=filtertype.assignable_type))

There are five types of filtertype

ANNOTATION, Assignable_type, ASPECTJ, REGEX, CUSTOM

Use

Build a Dog class

 Public class Dog {    publicvoid  init () {        System.out.println ("--------init------"  );    }      Public void destory () {        System.out.println ("--------destory------");}    }
View Code

Add a Dogconfig configuration class

@Configuration  Public class dogconfig {    = "Init", Destroymethod = "Destory")    public  Dog createdog () {        /c8>returnnew  Dog ();}    }
View Code

Add a scan configuration class

@ComponentScan (basepackages= "com.lhx.spring.spring", [email protected] (type=filtertype.assignable_type,classes= Dogconfig. class ) ) @Configurationpublicclass  annotationscan {}
View Code

Of course, you can also directly specify the class type with annotations, such as Usercontroller.class

Use

 Public classAnnotationClient2 { Public Static voidMain (string[] args) {Annotationconfigapplicationcontext context=NewAnnotationconfigapplicationcontext (Annotationscan.class); System.out.println (Context.getbean (Car).class)); System.out.println (Context.getbean (Cat.class)); System.out.println (Context.getbean (Dog).class)); System.out.println (Context.getbean (Animal.class)); System.out.println (Context.getbean (User.class));    Context.close (); }}
View Code3. Get Bean3.1, get it by type
System.out.println (Annotationconfigapplicationcontext.getbean (Mybean.  Class));
3.2. Access by name
System.out.println (Annotationconfigapplicationcontext.getbean ("Createmybean")); // default is method name

Note: The default is the method name configured in 1

You can also annotate the Bean with the specified: @Bean (name= "Mybean"), specifying that the default method name cannot be used after the

System.out.println (Annotationconfigapplicationcontext.getbean ("Mybean")); // specify a specific name

Where: The default is Singleton, @Scope ("prototype") is not a single case

such as 1, Method two, show

    System.out.println (Annotationconfigapplicationcontext.getbean (Jeep).  Class));    System.out.println (Annotationconfigapplicationcontext.getbean ("Createrunnablefactorybean"));

This is the specific bean, how to get the project Bean

    System.out.println (Annotationconfigapplicationcontext.getbean (Runnablefactorybean.  Class)); // type get    System.out.println (Annotationconfigapplicationcontext.getbean ("&createrunnablefactorybean")); // Name Acquisition

& Can get reason: annotationconfigapplicationcontext→genericapplicationcontext→abstractapplicationcontext→

Configurableapplicationcontext→applicationcontext→listablebeanfactory→beanfactory

Iii. annotation-based development Bean,bean initialization destruction 1, initialization implementation of Initializingbean, destruction implementation Disposablebean
 Public class Cat  implements  initializingbean,disposablebean{    @Override    publicvoid  throws  Exception {        System.out.println ("----------afterpropertiesset--------") ;            }    @Override    publicvoidthrows  Exception {        System.out.println ( "----------destroy--------");}            }
View Code2, injection time to achieve,

Top a init,destory in the class, @bean configuration in config configuration;

    @Bean (initmethod= "Init", destroymethod= "Destory")    public  Dog createdog () {          Returnnew  Dog ();    
View Code3. Using the annotations provided by jsr250 in Java, @PostConstruct, @PreDestroy
 Public class Animal {    @PostConstruct    publicvoid  initial () {        System.out.println ( "--------initial------");    }    @PreDestroy    publicvoid  close () {        System.out.println ("-------- Close------");}    }
View CodeIv. Bean Assembly, note 1, use @component annotations, no clear role

Add @component annotations on class, and in the Annotationconfigapplicationcontext, the parameters can be added.

New Annotationconfigapplicationcontext (                myconfig. class, User. class);

can be used. Note: The initialization method cannot be bound and so on.

        System.out.println (Annotationconfigapplicationcontext.getbean (User.  Class));        System.out.println (Annotationconfigapplicationcontext.getbean ("user"));

Type map can be obtained via Getbeansoftype

System.out.println (Annotationconfigapplicationcontext.getbeansoftype (User.  Class));

{[Email protected]}

If it is injected through config, then the fetch cannot be obtained by using the type, there are many do not know to create that, you can use the name to get

2. Other annotations can be used

@Repository generally used in the data access layer

@Service typically used in Service tiers

@Controller generally used in the control layer

V. Bean Dependency Injection 5.1, Spring mode, @Autowired
    @Autowired    private Userdao Userdao;

If there are multiple

1, name method, you can use Getbeansoftype to get the name, and then specify the name injection

    @Autowired    @Qualifier ("Userdao")    private Userdao Userdao;

2, in one of the increase @primary, the default will find this.

5.2, JSR 250 Way, @Resource5.3, JSR 330 way, @Inject
<Dependency>    <groupId>Javax.inject</groupId>    <Artifactid>Javax.inject</Artifactid>    <version>1</version></Dependency>

Code Address: Https://github.com/bjlhx15/spring-boot.git

002-spring4 Quick Start "container assembly"

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.