Bean的实现
之前是使用 bean 的标签进行bean注入,但在实际开发中我们一般都会使用注解
配置扫描哪些包下的注解
<context:component-scan base-package="com.dream.pojo"/>
在指定包下编写类,增加注解,将这个类交给Spring管理装配
@Component("user")
public class User {
public String name = "张三";
}
测试
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
System.out.println(user.name);
使用注解注入属性
不用提供set方法,直接在属性名上添加@value(“值”)
@Component("user")
public class User {
@Value("张三")
public String name ;
}
如果提供了set方法,在set方法上添加@value(“值”);
@Component("user")
public class User {
public String name ;
@Value("张三")
public void setName(String name) {
this.name = name;
}
}
衍生注解
@Component三个衍生注解:@Controller:web层,@Service:service层,@Repository:dao层
自动装配注解在上一篇已经讲过
作用域注解@scope
singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂,所有的对象都会销毁。
prototype:多例模式。关闭工厂 ,所有的对象不会销毁,内部的垃圾回收机制会回收
使用配置类进行配置
新建实体类
package com.dream.pojo;
import org.springframework.stereotype.Component;
@Component
public class Dog {
public String name = "旺财";
}
配置类
package com.dream.config;
import com.dream.pojo.Dog;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
public class MyConfig {
@Bean
public Dog dog(){
return new Dog();
}
}
测试
import com.dream.config.MyConfig;
import com.dream.pojo.Dog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
Dog dog = (Dog) context.getBean("dog");
System.out.println(dog.name);
}
}
若还有其他配置类
package com.dream.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig2 {
}
导入即可
@Import(MyConfig2.class)
实际开发中我们可以用xml管理bean,用注解注入属性
如果不扫描包,就需要手动配置bean,如果不加注解驱动,则注入的值为null