目录
bean标签定义bean
所需pom
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
pojo
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
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 ">
<!--使用spring来创建对象,在spring这些都成为Bean-->
<bean id="user" class="com.luban.User">
</bean>
</beans>
测试
public class Main {
public static void main(String[] args) {
User user = new User();//对象 Bean肯定是对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
User user1 = context.getBean("user", User.class);
System.out.println(user1);
}
}
输出
com.luban.User@57baeedf
@Bean定义bean
新建config
public class config {
@Bean
public User user(){
return new User();
}
}
测试:
public class Main {
public static void main(String[] args) {
User user = new User();//对象 Bean肯定是对象
/* ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");*/
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(config.class);
User user1 = context.getBean("user", User.class);
System.out.println(user1);
}
}
输出:com.luban.User@3dfc5fb8
通过@Component定义bean
修改config
@ComponentScan("com.luban")
public class config {
/* @Bean
public User user(){
return new User();
}*/
}
user
@Component
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试:
public class Main {
public static void main(String[] args) {
User user = new User();//对象 Bean肯定是对象
/* ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");*/
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(config.class);
User user1 = context.getBean("user", User.class);
System.out.println(user1);
}
}
输出:com.luban.User@3ecd23d9
说明:将@Compoent换成@Serivice也行
点开@Service注解,发现包含了@Compoent,因此@Service也有@Compoent的功能
BeanDefinition定义一个Bean
将User类上的@Component删掉,
同时
public class Main {
public static void main(String[] args) {
User user = new User();//对象 Bean肯定是对象
/* ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");*/
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
beanDefinition.setBeanClass(User.class);
context.registerBeanDefinition("user",beanDefinition);
//去实例化bean
context.refresh();
User user1 = context.getBean("user", User.class);
System.out.println(user1);
}
}
输出:com.luban.User@5abca1e0
总结:前三种定义bean底层都是通过第四种形式来实现定义bean的