(一) Spring学习笔记之三种方式声明bean

mac2022-06-30  73

一.使用注解@Configuration

1.创建实体Author.class:

public class Author { private String firstName; private String lastName; public Author() { super(); // TODO Auto-generated constructor stub System.out.println("Author constructor"); } //省略 setter, getter }

 

2.创建配置AppConfig.class:

@Configuration//告诉ApplicationContext这个类定义了bean public class AppConfig { @Bean public Author author1() { return new Author(); } }

 

3.创建Main.class,读取配置:

public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);//读取AppConfig Author author = (Author) context.getBean("author1");//获取方法名为author1的bean System.out.println(author); } }

 

4.控制台输出:

Author constructor

说明在初始化的时候spring读取配置并调用@bean注解的方法author1,返回new Author并创建了实体Author,在构造函数处打印输出

 

5.源码地址:https://github.com/Jamie956/simpleSpring/tree/master/01-configBean

 

二.使用XML

1.创建实体Employee.class:

public class Employee { private String name; public void displayName() { System.out.println(name); } //省略setter, getter }

 

2.创建配置文件beans.xml:

<?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-4.3.xsd"> <bean id="employee" class="com.example.Employee"> <property name="name" value="test spring"></property> </bean> </beans>

id:当我们读取beans.xml时,就是靠id来找到这个bean

class:就是这个bean代表的实体

property:给这个bean的name变量赋值“test spring”

 

3.创建Main.class读取配置:

public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");//读取beans.xml Employee employee = (Employee) context.getBean("employee");//获取id为employee的bean employee.displayName();//调用employee的方法 } }

 

4.控制台输出:

test spring

 

5.源码地址:https://github.com/Jamie956/simpleSpring/tree/master/01-xmlBean

 

三.使用注解@Component

1.创建实体Author.class:

@Component//能让applicationcontext扫描到 public class Author { private String firstName = "Steven"; private String lastName = "King"; //省略setter, getter }

 

2.读取配置:

public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan("com.example");//扫描com.example包下包含@component注解的类 context.refresh(); Author author = context.getBean(Author.class); System.out.println(author); } }

 

3.控制输出:

com.example.entity.Author@4e7dc304

说明Author已经创建

 

源码地址: https://github.com/Jamie956/simpleSpring/tree/master/01-annotationBean

转载于:https://www.cnblogs.com/jamie956/p/9017145.html

最新回复(0)