SPRINGIOC of Technical Summary

Source: Internet
Author: User

1) SPRINGIOC Core Simulation implementation

Idea: When initializing a spring container, read the defined bean information from the configuration file and deposit it into the spring container based on the configuration property initialization.

When a bean is needed, it is obtained directly from the container through the ID.

Steps:

A) Create a Java project that requires a dependency package (primarily used to parse XML files) such as:

b) First simulate spring to define two simple beans in the configuration file My-ioc.xml, as follows:

c) Follow the above ideas to simulate spring implementation of our own IOC container Myioccontext, implemented as follows:

    1. public class Myioccontext {

    2. Private final map<string, object> beanmap = new hashmap<string, object> ();

    3. Public Myioccontext (String fileName) {

    4. Init (fileName);

    5. }

    6. private void init (String fileName) {

    7. }

    8. Public Object Getbean (String ID) {

    9. return Beanmap.get (ID);

    10. }

    11. }

Where Init is implemented as follows:

d) Test:

    1. public class Myioctest {

    2. Private Myioccontext CTX = null;

    3. @Before

    4. public void SetUp () throws Exception {

    5. CTX = new Myioccontext ("My-ioc.xml");

    6. }

    7. @Test

    8. public void Testioc () throws Exception {

    9. Hello hello = (hello) ctx.getbean ("Hello");

    10. Hello.say ("My IOC Context");

    11. }

    12. }

The result is:

At this point, the core implementation of the IOC container is complete.

2) Spring Dependent injection method

A) Manual injection

    • Constructor injection.

    • Property setter injection.

    • Use field injection (for annotation mode) as follows:

    1. @Autowired: Injecting by type

    2. @Resource: Injected by name if it fails and then injected by type. If name is specified, it is injected by name only.

b) Automatic injection

Configuration in XML, <bean id= "" class= "" autowire= "Bytype"/>

SPRINGIOC of Technical Summary

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.