spring注解目录
Spring注解包括了许多的spring相关注解的解释和应用。
目录
概述
@configuration和@bean注解的含义和使用方式。
当然这之前需要在pom.xml中引入,springcontext。
注解方式
@configuration
主要是告诉spring,我是配置类,下面能配置很多东西。
@bean
主要是写在@configuration下面的,声明了下面能配置很多东西,@bean就说,我要配置一个容器,里面装一个人的名字和年龄。
package config;
import bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration//告诉spring这是一个配置类
public class MainConfig {
//给容器注册一个Bean
@Bean("person02")
public Person person(){
return new Person("李四","20");
}
}
person类的声明
package bean;
public class Person {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
public Person(String name, String age) {
this.name = name;
this.age = age;
}
public Person() {
super();
}
}
调用方式
怎么调用获取容器中的值,我们需要new一个AnnotationConfigApplicationContext对象,这个对象负责调用,注册容器的地址。
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
这下拿到,容器中的值了
然后我不仅想要拿到值,我还要拿到容器,调用容器的值,肯定就要找到这个容器,这时候通过getBeanNamesForType这个方法,就能拿到容器的id,也就是他的名字person。
容器id默认是方法名。可以给他改名字吗?在@bean("我改名字了person02"),这样就完成了改名。
最后附上测试类的全代码。
package test;
import bean.Person;
import config.MainConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
for(String name: namesForType){
System.out.println(name);
}
}
}
最后附上CSDN下载demo文件的链接(除此之外还包括了,之后的@componentscan注解,但是代码都是全的),可以参考。