In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you the relevant knowledge about the basic usage of IOC of Spring. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
1 、 spring_helloworld
Use maven to build the project (Mavaen)
Add corresponding pom dependencies
Pom.xml
Org.springframework spring-context 5.2.3.RELEASE
Write code
Person.java
Public class Person {private int id; private String name; private int age; private String gender; public int getId () {return id;} public void setId (int id) {this.id = id; public String getName () {return name; public void setName (String name) {this.name = name Public int getAge () {return age; public void setAge (int age) {this.age = age; public String getGender () {return gender; public void setGender (String gender) {this.gender = gender @ Override public String toString () {return "Person {" + "id=" + id + ", name='" + name +'\'+ ", age=" + age + ", gender='" + gender +'\'+'}';}
test
MyTest.java
Public class MyTest {public static void main (String [] args) {ApplicationContext context = new ClassPathXmlApplicationContext ("ioc.xml"); Person person = (Person) context.getBean ("person"); System.out.println (person);}}
Summary:
Be sure to add the configuration file to the classpath. When you use idea to create a project, you need to create objects under the resource directory to assign values to properties. Objects that are implemented through the setter method are singleton when stored in the IOC container. If you need to modify properties (default singleton, you can change multiple instances) the object has been created when the Spring container is created. It is not created when you need it (the object is created when Application is created) ApplicationContext is the interface of the IOC container, through which you can get the objects created in the container.
2. The acquisition of spring object and the way of attribute assignment.
1. Get the objects in the IOC container through the id of bean (already used above)
Be sure to add the configuration file to the classpath and put it in the resource directory when you create a project using idea
Creating an object to assign a value to a property is achieved through the setter method
Objects are singleton when they are stored in the IOC container. If you need more than one instance, you need to modify the attributes (default singleton, you can change multiple instances)
The object is created when the Spring container is created, not when it is needed (the object is created when Application is created)
ApplicationContext is the interface of the IOC container. You can use this object to obtain the objects created in the container.
2. Obtain the object through the type of bean
ApplicationContext context = new ClassPathXmlApplicationContext ("ioc.xml"); Person bean = context.getBean (Person.class); System.out.println (bean)
Note: when looking for objects through the type of bean, there cannot be two bean objects of the same type in the configuration file. If so, you can use the following methods
Public class MyTest {public static void main (String [] args) {ApplicationContext context = new ClassPathXmlApplicationContext ("ioc.xml"); Person person = context.getBean ("person", Person.class); System.out.println (person);} 3. Assign a value to the bean object through the constructor
Summary:
Constructor-arg adds constructors to the person class
The name attribute can be omitted when using constructor assignment, but it is required that it must be filled in strictly according to the order of constructor parameters
If you want to add parameter values out of order, you can use them with the index attribute
When there are different types of constructors with the same number of parameters, you can use type to enforce the type.
There are two overloaded constructors, and the latter overrides the previous constructor.
Five attribute values in constructor-arg: value: assignment name: member attribute ref: reference other objects through ref, reference external beanindex: if you want to add parameter values out of order, you can use type with the index attribute: when there are multiple constructors with the same number of parameters and different types, you can use type to enforce the type
Ioc.xml
Set the age type of person to the Integer type public Person (int id, String name, Integer age) {this.id = id; this.name = name; this.age = age; System.out.println ("Age"); the constructor following} / / overrides the previous constructor. Public Person (int id, String name, String gender) {this.id = id; this.name = name; this.gender = gender; System.out.println ("gender");} 4. Assign values to bean through namespaces to simplify the writing of attribute declarations in the configuration file
P imports namespaces, and c namespaces, simpler naming, that's all. 、
1. Import namespaces-- xml can be used with some specifications.
2. Add configuration ioc.xml
5. Assign values to complex types (key points)
Summary:
Assign values to various complex types, such as collections, arrays, other objects, and so on.
Create the following classes: Person.java, Book.java, Address.java as a demonstration
Person.java
Import java.util.*;public class Person {private int id; private String name= "dahuang"; private int age; private String gender; private Address address; private String [] hobbies; private List books; private Set sets; private Map maps; private Properties properties; / / has not used this data type public Person (int id, String name, int age, String gender) {this.id = id; this.name = name This.age = age; this.gender = gender; System.out.println ("parametric constructor");} public Person (int id, String name, int age) {this.id = id; this.name = name; this.age = age; System.out.println ("Age");} public Person (int id, String name, String gender) {this.id = id This.name = name; this.gender = gender; System.out.println ("gender");} public Person () {} public int getId () {return id;} public void setId (int id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name } public int getAge () {return age;} public void setAge (int age) {this.age = age;} public String getGender () {return gender;} public void setGender (String gender) {this.gender = gender;} public Address getAddress () {return address;} public void setAddress (Address address) {this.address = address } public List getBooks () {return books;} public void setBooks (List books) {this.books = books;} public Map getMaps () {return maps;} public void setMaps (Map maps) {this.maps = maps;} public Properties getProperties () {return properties;} public void setProperties (Properties properties) {this.properties = properties } public String [] getHobbies () {return hobbies;} public void setHobbies (String [] hobbies) {this.hobbies = hobbies;} public Set getSets () {return sets;} public void setSets (Set sets) {this.sets = sets } @ Override public String toString () {return "Person {" + "id=" + id + ", name='" + name +'\'+ ", age=" + age + ", gender='" + gender +'\'+ ", address=" + address + " Hobbies= "+ Arrays.toString (hobbies) +", books= "+ books +", sets= "+ sets +", maps= "+ maps +", properties= "+ properties +'}' }}
Book.java
Public class Book {private String name; private String author; private double price; public Book () {} public Book (String name, String author, double price) {this.name = name; this.author = author; this.price = price;} public String getName () {return name;} public void setName (String name) {this.name = name } public String getAuthor () {return author;} public void setAuthor (String author) {this.author = author;} public double getPrice () {return price;} public void setPrice (double price) {this.price = price } @ Override public String toString () {return "Book {" + "name='" + name +'\'+ ", author='" + author +'\'+ ", price=" + price +'}';}}
Address.java
Public class Address {private String province; private String city; private String town; public Address () {} public Address (String province, String city, String town) {this.province = province; this.city = city; this.town = town; public String getProvince () {return province; public void setProvince (String province) {public String getCity () {return city Public void setCity (String city) {public String getTown () {return town Public void setTown (String town) {@ Override public String toString () {return "Address {" + "province='" + province +'\'+ ", city='" + city +'\'+ ", town='" + town +'\'+'}';}
Ioc.xml
All assignments to complex types are done within the property tag. Assigned to null 2. External reference ref 3. Quote internal bean 4. Assign a value of 5. 0 to list. Assign a value of 11122222226 to set. Assign a value of 7. 0 to map. Assign book movie game to an array
Ioc.xml
Aaa 222 book movie game 111 222 222 6 、 Configuration of inheritance relationship bean (temporarily unavailable)
It means that bean can inherit
Parent: specifies which bean the configuration information of bean is inherited from
Parson2 inherits parson and modifies name
Abstract: abstract bean. The value is in it, but it cannot be instantiated. Abstract= "true"
It doesn't seem to be of any use to demonstrate it yourself.
Ioc.xml
7. Dependency created by bean object (not needed temporarily)
Bean objects are created according to the order of bean in the configuration file, or you can use the depend-on tag to determine the order
8. Whether the scope control of bean is a single case (general two)
Minutiae difference: (minutiae in an interview)
Prototype: multi-instance bean is not created when the container starts, but only when the object is obtained.
Singleton: the object is created before the container launches.
Four scopes singleton Singleton (default mode) prototype multiple mode spring 4.x version: request: every time a request is sent there is a new object session: each send session has a new object these two ways are rarely used. Test singleton Person2 person2 = context.getBean ("person2", Person.class); Person3 person3 = context.getBean ("person3", Person.class); System.out.println (Person2== person3); / / ture
Ioc.xml
9. Create bean objects using factory schema
Static factory and instance factory difference?
Static factory: the factory itself does not need to create an object, but it can be called through a static method, object = factory class. Static factory method name ()
Instance factory: the factory itself needs to create an object, factory class factory object = new factory class; factory object .get object name ()
Advantages and disadvantages:
Instance factories are easier to expand.
PersonStaticFactory.java
Public class PersonStaticFactory {/ / static factory class public static Person getPerson (String name) {Person person = new Person (); person.setId (1); person.setName (name); return person;}}
Ioc.xml
Test.java
Factory creation: use this without the PersonStaticFactory class, because it is created using the factory method. Person2 person2 = context.getBean ("person2", Person.class); System.out.println (Person2)
PersonInstanceFactory.java
The public class PersonInstanceFactory {/ / instance factory class does not add staticware! Public Person getPerson (String name) {Person person = new Person (); person.setId (1); person.setName (name); return person;}}
Ioc.xml
10. Inherit FactoryBean to create objects (generally not needed, see a lot in the source code)
BeanFactory interface, specification
FactoryBean: gets the unique object.
Objects created by yourself can also be managed by spring.
It means that what I have created can be handed over to Spring management as follows >
Use:
1) implement FactoryBean interface
2) three methods:
Factory method, which returns the object to be created
Returns the type of object
Whether it is a singleton object
3) send it to spring to configure the ioc.xml below
Summary:
Create a supplement to the object, create it when you use it, don't create it, don't create it. It has nothing to do with single and multiple cases.
Don't use it yourself. The source code will be used a lot.
11. Initialization and destruction methods of bean objects (understand)
Initialization is different from single and multiple cases: (generally no one uses it, interview knows)
If bean is a singleton, the container will be created at startup and the created bean will be destroyed when closed
If the bean is multiple instances, the object is created when it is acquired, and no call is made when it is destroyed.
12. Configure the pre-and post-processing methods of bean object initialization methods (understand)
POSTxxxx interface
13. Spring creates third-party bean objects (configure database connection pooling)
1. Import the pom file of the database connection pool
Com.alibaba druid 1.1.21 mysql mysql-connector-java 5.1.47
2. Write a configuration file
3. Write test files
Public class MyTest {public static void main (String [] args) throws SQLException {ApplicationContext context = new ClassPathXmlApplicationContext ("ioc3.xml"); DruidDataSource dataSource = context.getBean ("dataSource", DruidDataSource.class); System.out.println (dataSource); System.out.println (dataSource.getConnection ());}}
4. Spring references external configuration files
5. Spring automatic assembly based on xml file
There is an address class in front of you, and in ioc.xml, you use propotery assembly.
Now automatically assemble:
How did it happen?
ByName: the first subtitle must be lowercase according to the set method.
Type: assemble according to type, if you have more than one type, an error will be reported.
When another object needs to be referenced in an object, we configured it manually through the property tag in the previous configuration. In fact, we also provide a very powerful feature in spring, which is automatic assembly, which can be configured according to the rules we specify. The configuration methods are as follows:
Default/no: do not automatically assemble
ByName: assemble by name, use the attribute name as id to find the component in the container, assign it, and assemble null if you can't find it.
ByType: assemble by type, and find the component in the container based on the type of the attribute. If there are multiple bean objects of the same type, an exception will be reported. If not, null will be assembled.
Constructor: assemble according to the constructor, first assemble according to the type with parameter constructor parameters, and directly assemble null; if you find more than one according to the type, then use the parameter name as id to continue matching, assemble if you find it, and assemble null if you can't find it.
6. The use of SpEL (simple syntax sugar, convenient to write bean)
Slightly: you can go to see it only when the company asks you to use it, but it's no use if you don't need it now.
7. Annotation application of SpringIOC
Note identification in Spring:
Spring contains four main components to add comments: @ Controller: controller, it is recommended to add this note to the controller layer (for accepting user requests for web) @ Service: business logic, it is recommended to add this note to the business logic layer @ Repository: warehouse management, it is recommended to add this note to the data access layer @ Component: add this note to * * components * * that do not belong to the above basic level * * (if you don't know anything, add this note)
Steps for the use of notes
Using annotations requires the following steps:
1. Add any of the above four comments
2. Add components that scan and annotate automatically, which depends on the context namespace.
3. Add the automatic scanning tag context:component-scan (all classes under the current package are scanned)
Question: when we use annotations, we don't define id and class. How does he identify them?
Default class names are initials, lowercase, but can be aliased. Generally, no one does so. Add value = "xxxxxx" in parentheses of the annotation identification, such as @ Controler (value = "the name of the class can be changed").
The scan package can be used to divide the fine grain of ploughing (useless)
Use @ AutoWired for automatic injection (difficult to understand, watch the video)
Interview questions:
Note: when using AutoWired annotations, automatic assembly is implemented according to type.
1. If only one is found, assign the value directly
2. If it is not found, an exception is thrown directly.
3. If more than one is found, it will continue to match according to the variable name as id
1. Assemble directly on the matching
2. If there is no match, the exception will be reported directly.
You can also use the @ Qualifier annotation to specify the name of the id so that spring does not use the variable name, and there are two situations when using the @ Qualifier annotation:
1. If you find it, assemble it directly.
2. If you can't find it, you will report an error.
@ AutoWired can be defined on the method
Annotations for automatic assembly @ AutoWired,@Resource
Interview questions:
When using autoassembly, you can use @ AutoWired annotations as well as @ Resource annotations. You need to know the difference between the two annotations.
1. @ AutoWired: is the annotation provided in spring, and @ Resource: is the annotation defined in jdk, relying on the java standard
2. @ AutoWired is assembled by type by default, and dependent objects must exist by default. @ Resource matches by name by default, and you can specify the name attribute.
3. @ AutoWired is only suitable for spring framework, while @ Resource is more extensible.
These are all the contents of the article "what is the basic usage of IOC for Spring". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.