目录
1. xml声明
通过xml文件将POJO配置成一个Bean,然后通过XmlApplicationContext读取配置。
package com.test;
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayName() {
System.out.println(name);
}
}
<?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.test.Employee">
<property name="name" value="test spring"></property>
</bean>
</beans>
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Customer {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Employee obj = (Employee) context.getBean("employee");
obj.displayName();
}
}
2. Java配置类
在Config类中通过方法配置Bean,然后通过AnnotationConfigApplicationContext读取配置。
public class BeanDeclaredInAppConfig {
public void sayHello() {
System.out.println("Hello, World from BeanDeclaredInAppConfig !");
}
}
package com.stackoverflow.documentation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public BeanDeclaredInAppConfig beanDeclaredInAppConfig() {
return new BeanDeclaredInAppConfig();
}
}
public class Main {
public static void main(String[] args) {
//initializing the Application Context once per application.
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
BeanDeclaredInAppConfig beanDeclaredInAppConfig = applicationContext.getBean(BeanDeclaredInAppConfig.class);
beanDeclaredInAppConfig.sayHello();
}
}
3. 注解
通过注解的方式配置Bean,通过包扫描的方式注册Bean
这里通过@Component注解配置了一个Bean
@Component
public class BeanDeclaredByAnnotation {
public void sayHello() {
System.out.println("Hello, World from BeanDeclaredByAnnotation !");
}
}
配置类中开启包扫描@ComponentScan
package com.stackoverflow.documentation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.stackoverflow.documentation")
public class AppConfig {
}
可以通过Context获取Bean
public class Main {
public static void main(String[] args) {
//initializing the Application Context once per application.
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
BeanDeclaredByAnnotation beanDeclaredByAnnotation = applicationContext.getBean(BeanDeclaredByAnnotation.class);
beanDeclaredByAnnotation.sayHello();
}
}