The first step is to create a Maven project. Spring is also based on Maven.
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.
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.
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>
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>
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
.
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,
BeanFactory only provides Basic access to the functions of
Bean objects, and
ApplicationContext in 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.
BeanFactoryLoads on demand
Bean, which is a lazy way,
ApplicationContext It's the hungry way. All
Bean will 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!