//@Scope(scopeName = ConfigurableBeanFactory.SCOPE_SINGLETON) //默认单例模式
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) //多例模式
@Component // <Bean id="JavaBean" class="JavaBean" >
public class JavaBean {
@Autowired //<property UserService> boolean required () default true必须有组件否则报错
//@Autowired(required = false) //佛系装配 可以没有组件,也不报错,不推荐使用,会出现空指针
//自动装配注解(DI) 1.IOC容器中查找复合类型的对象 2.设置给当前属性(DI)
@Qualifier(value="userServiceImpl") //有多个组件时可以添加Qualifier来区别组件名称id,不能单独使用
@Resource //等于 AutoWired + Qualifier
private UserService userService;
@Resource(name = "userServiceImpl")
private UserService userService1;
/*
<bean id="" class="">
<property name="" value="">
</bean>
*/
//方案一:直接赋值
private String name="二狗子";
//方案二:使用注解赋值,读取外部配置
@Value("19")
private int age;
//可以用 :添加默认值admin
@Value("${jdbc.username:admin}")
private String userName;
@Value("${jdbc.password}")
private String passWord;
//周期方法命名随意 public void修饰 没有形参
@PostConstruct
public void init(){
System.out.println("inti...........");
}
@PreDestroy
public void destroy(){
System.out.println("destroy..........");
}
}
@Controller //<bean >
public class XxxController {
}
@Repository
public class XxxDao {
}
@Service
public class XxxService {
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1. 普通配置包扫描-->
<!-- base-package指定那些包下的注解要生效,指定ioc容器去哪些包下查找注解,放到ioc容器中,多个包用 , 隔开,指定包,包括子包-->
<!-- <context:component-scan base-package="com.atguigu.ioc_01"></context:component-scan>-->
<!-- 2. 指定排除注解-->
<!-- <context:component-scan base-package="com.atguigu">-->
<!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>-->
<!-- </context:component-scan>-->
<!-- 3. 指定包含注解-->
<!-- 扫描包下的所有注解, 需要让扫描所有包这句初始的不生效-->
<context:component-scan base-package="com.atguigu" use-default-filters="false">
<!-- 只扫描包下的Repository注解-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
推荐阅读: