Bean的加载方式
Bean的加载方式
文章目录
- Bean的加载方式
- bean的xml方式声明
- bean的加载方式二:XML+注解当时声明bean
- bean的加载方式三:注解方式声明配置类
- bean加载方式扩展——FactoryBean
bean的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">
<!-- xml方式声明自己开发的bean-->
<bean id="cat" class="com.itheima.bean.Cat"/>
<bean class="com.itheima.bean.Dog"/>
<!-- xml声明第三方开发的Bean-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"/>
<bean class="com.alibaba.druid.pool.DruidDataSource"/>
<bean class="com.alibaba.druid.pool.DruidDataSource"/>
</beans>
bean的加载方式二:XML+注解当时声明bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 指定加载Bean的位置,Component-->
<context:component-scan base-package="com.itheima.bean,com.itheima.config"/>
</beans>
//@Component
@Configuration
public class DbConfig {
@Bean
public DruidDataSource dataSource(){
DruidDataSource ds = new DruidDataSource();
return ds;
}
}
bean的加载方式三:注解方式声明配置类
@ComponentScan({"com.itheima.bean","com.itheima.config"})
public class SpringConfig3 {
}
要使用AnnotationConfigApplicationContext加载bean了
public class App3 {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig3.class);
String[] names = ctx.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
}
}
bean加载方式扩展——FactoryBean
public class DogFactoryBean implements FactoryBean<Dog> {
@Override
public Dog getObject() throws Exception {
return new Dog();
}
@Override
public Class<?> getObjectType() {
return Dog.class;
}
@Override
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}