


Java Spring framework creation project and Bean storage and reading example analysis
1.Creation of Spring project
1.1 Create Maven project
The first step is to create a Maven project. Spring is also based on Maven.
1.2 Add spring dependency
The second step is to add Spring support in the Maven project (spring-context , spring-beans)
Add dependencies in the pom.xml
file.
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.3.RELEASE</version> </dependency> </dependencies>
Refresh and wait for loading to complete.
1.3 Create the startup class
The third step is to create the startup class and main for simple testing
In the java directory Just create the class and write the code, because here we only demonstrate how to create a Spring project and introduce the simple use of Spring. We don't rely on Tomcat or anything else. It is more intuitive to write a Main class directly.
1.4 Configuring domestic sources
Because foreign sources are unstable, introducing spring dependencies in the second step may fail, so the following describes how to configure domestic mirror sources.
Ready-made settings.xml file link:
Address 1
Address 2: Extraction Code: 9thv
If you already have a settings file but do not configure mirror
, the configuration content is as follows:
<mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror>
2. Store or read Bean objects
2.1 Add spring configuration file
Add spring configuration file (only required for the first time, you can ignore this step if it is not the first time)
Right-click the resources directory and create a new .xml
Configuration file, the file name is recommended spring.xml
or spring-config.xml
.
Create a spring.xml configuration file, configuration content:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
2.2 Create Bean object
The first step is to create Bean
Object.
For example, if we want to inject a User
object, we first create a User
class.
package com.bean; public class User { public void sayHi(String name) { System.out.println("你好!" + name); } }
Inject Bean
into spring through the configuration file, that is, inject it through the following statement in the spring configuration file.
<bean id="user" class="com.bean.User"></bean>
Objects in spring are stored through key-value pairs, where key
is id
and value
is class
.
Naming convention: id
uses small camel case naming, such as userid
, class
uses large camel case naming, such as userId
.
2.3 Reading Bean Object
If you want to read the Bean
object from spring, you must first get the spring context object, which is equivalent to getting spring. Then obtain the Bean
object that needs to be used through the method provided by the spring context object. Finally, you can use the Bean
object.
import com.bean.User; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { //1.得到上下文对象 ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); //2.获取bean对象,此处是根据id获取 User user = (User) context.getBean("user"); //3.使用bean user.sayHi("zhangsan"); } }
Run result:
Hello!zhangsan
Process finished with exit code 0
You can also use Bean factory ( old) to get the Bean.
import com.bean.User; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main2 { public static void main(String[] args) { //1.得到Bean工厂 BeanFactory factory = new XmlBeanFactory(new ClassPathResource("spring.xml")); //2.获取Bean User user = (User) factory.getBean("user"); //3.使用 user.sayHi("李四"); } }
Although the Bean factory
Run result:
Hello! Li Si
Process finished with exit code 0
DiscoveredApplicationContext# Both ## and
BeanFactory can obtain
Bean from the container, and both provide the
getBean method. Then the problem arises,
ApplicationContext and
BeanFactoryWhat is the difference?
Bean from the container, and both provide the
getBean method.
BeanFactory
is the parent class of
ApplicationContext,
BeanFactoryonly provides Basic access to the functions of
Beanobjects, and
ApplicationContextin addition to having all the functions of
BeanFactory, also has the implementation of other additional functions, such as internationalization, resource access and other functions accomplish.
- It is different in terms of performance,
BeanFactory
Loads on demand
Bean, which is a lazy way,
ApplicationContextIt's the hungry way. All
Beanwill be loaded when creating, ready for use.
我们在bean目录下添加一个Blog
类,并完善Blog
与User
类的构造方法,当类被构造时会发出一些信号,在获取上下文或工厂时根据这些信号让我们感知到它是否会被构造。
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main3 { public static void main(String[] args) { //1.得到上下文对象 ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); } }
运行结果:
ApplicationContext创建时,会将所有的对象都构造,饿汉的方式。
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main4 { public static void main(String[] args) { //1.得到Bean工厂 BeanFactory factory = new XmlBeanFactory(new ClassPathResource("spring.xml")); } }
BeanFactory创建时,什么都没有,说明是懒汉的方式。
ApplicationContext
中的多种getBean
方法:
方法1:根据 bean name
获取bean
。
User user = (User) context.getBean("user");
方法2:根据bean type
获取bean
。
User user = (User) context.getBean(User.class);
只有beans中只有一个类的实例没有问题,但是个有多个同类的实例,会有问题,即在spring中注入多个同一个类的对象,就会报错。
我们来试一试,首先在Spring配置文件,注入多个User
对象:
然后我们再通过这种方式来获取对象,我们发现报错了,报错信息如下:
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.bean.User' available: expected single matching bean but found 3: user,user1,user2
抛出了一个NoUniqueBeanDefinitionException
异常,表示注入的对象不是唯一的。
方法3:综合上述两种,可以根据bean name
与bean type
来获取bean
相比方法1,更加健壮。
User user = context.getBean("user", User.class);
The above is the detailed content of Java Spring framework creation project and Bean storage and reading example analysis. For more information, please follow other related articles on the PHP Chinese website!

Discussion on the differences between JSON serialization and JDK serialization in storage In the fields of programming and data storage, serialization is to convert objects into storable or transferable formats...

Solving the intersection coordinates of two line segments in three-dimensional space This article will explore how to solve the intersection coordinates of two line segments in three-dimensional space, especially when these two lines...

How to build HTTP request response monitoring software? This article will explore how to develop a software that can monitor relevant metrics in the client HTTP request and response process...

In IntelliJ...

How to solve the problem that Flink cannot find Python task script when submitting PyFlink job to YarnApplication? When you are submitting PyFlink jobs to Yarn using Flink...

Java array expansion and strange output results This article will analyze a piece of Java code, which aims to achieve dynamic expansion of arrays, but during operation...

Blank pages and proxy exceptions encountered when deploying front-end projects with Docker Nginx. When using Docker and Nginx to deploy front-end and back-end projects, you often encounter some...

Deployment method of external configuration files of SpringBoot3 project In SpringBoot3 project development, we often need to configure the configuration file application.properties...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use