标签:一个 注解 package http 方法 logs tag pos spring
学习地址:https://www.bilibili.com/video/BV1gW411W7wy?p=2
引用 spring4.0之二:@Configuration的使用
@Configuration定义配置类,类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
Maven项目结构:
引入spring context依赖:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
</dependencies>
非注解方式对比版:
创建实例 com.atguigu.bean.Person
package com.atguigu.bean;
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Person{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
}
在resources下创建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.xsd">
<!--注册容器实例-->
<bean id="person" class="com.atguigu.bean.Person">
<!--配置实例属性-->
<property name="age" value="18"></property>
<property name="name" value="zhangsan"></property>
</bean>
</beans>
测试:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:beans.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
使用配置文件注册容器的,可以从这个ClassPathXmlApplicationContext方法命名中看出,从ClassPath下Xml配置文件中加载ApplicationContext
使用注解的方式:
创建配置类com.atguigu.config.MainConfig
package com.atguigu.config;
import com.atguigu.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 设置为配置类
@Configuration
public class MainConfig {
// 在Bean注解中可以设置实例id
@Bean
public Person person(){
return new Person("lisi", 20);
}
}
测试:
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
AnnotationConfigApplicationContext 从 AnnotationConfig注解配置类 中 加载ApplicationContext
标签:一个 注解 package http 方法 logs tag pos spring
原文地址:https://www.cnblogs.com/zkzgogogo/p/14442963.html