Spring系列之Bean注解用法介绍

1、首先创建一个maven项目引入spring依赖

org.springframework spring-context 5.3.9

2、新建一个person.java 实体类

package com.spring.bean;

public class Person {
private String name;
private Integer age;
private String address;

public Person(String name, Integer age, String address) {
this.name = name;
this.age = age;
this.address = address;
}

public Person() {
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", address='" + address + '\'' +
'}';
}
}

3、新建配置类 TestBeanConfig.java

package com.spring.config;

import com.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestBeanConfig {
/*@Bean作用是注册一个Bean,类型为返回值的类型,默认是使用方法名作为id,可以自己定义
* value 可以自定义id,默认和方法名一致
* */
@Bean(value = "person1")
public Person person() {
return new Person("小王", 35, "北京");
}
}

4、resources 创建配置文件


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">






5、新建测试类TestBean.java 具体展示注解方式和配置方式的示例

package com.spring.test;

import com.spring.bean.Person;
import com.spring.config.TestBeanConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBean {
public static void main(String[] args) {
//配置文件方式
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("person.xml");
Person bean = (Person) applicationContext.getBean("person");
System.out.println("配置方式:");
System.out.println(bean);
// 注解方式 AnnotationConfigApplicationContext 注解的方式获取spring容器
AnnotationConfigApplicationContext annotationContext = new AnnotationConfigApplicationContext(TestBeanConfig.class);
Person annotationPerson = (Person) annotationContext.getBean("person1");
System.out.println("注解方式:");
System.out.println(annotationPerson);
// 用来获取Spring容器中指定类型的所有JavaBean的名称
String[] beanNamesForType = annotationContext.getBeanNamesForType(Person.class);
for (String item : beanNamesForType) {
System.out.println(item);
}
}

}

6、运行效果:

新闻名称:Spring系列之Bean注解用法介绍
网页网址:http://www.csdahua.cn/qtweb/news7/457457.html

网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网