@Autowired和New Keword以及Application上下文之间的差异来创建一个对象

时间:2015-06-18 12:14:54

标签: java spring

请任何人告诉我

之间的区别
@Autowired
CustomerService cService;

CustomerService cService=new CustomerService();

并且

private static  ApplicationContext applicationContext;
DefaultValueBean defaultValueBean = (DefaultValueBean) applicationContext.getBean("defaultValue");

2 个答案:

答案 0 :(得分:1)

执行CustomerService cService=new CustomerService();和其他两个语句之间的区别在于,在后两个语句中,Spring将管理已创建对象的生命周期及其依赖关系,而在前一种情况下,您将必须管理对象的生命周期及其所需的所有依赖项。

执行@Autowired CustomerService cService;DefaultValueBean defaultValueBean = (DefaultValueBean) applicationContext.getBean("defaultValue");之间的区别在于,在前一种情况下,Spring将根据自动装配模式查找bean,而在后面,您要求Spring寻找id配置为defaultValue

的bean

您可以查看依赖注入的Spring文档,以获得更详细的解释。

答案 1 :(得分:0)

根据我的理解,当您在Spring中使用Autowire声明bean时,您正在访问该对象的实例,该实例可从系统启动时获得。因此,如果您要在两个不同的类中访问它,您将访问同一个对象。

public class Class1(){ 
@Autowired
CustomerService cService;
} 

public class Class2(){
@Autowired
CustomerService cService;
}

public class Class3(){
CustomerService cService=new CustomerService();
}

声明了该对象的一个​​全新实例,因此如果您要在两个不同的类中执行此操作,那么它们将是完全独立的对象。

例如

StringBuilder sb = new StringBuilder();
foreach (DataRow row in dataTable.Rows)
{
   sb.AppendLine(row[0].ToString().PadRight(8, ' ') + "," + row[1].ToString().PadRight(4, ' ') + "," + row[2].ToString().PadRight(8, ' ') + "," + row[3].ToString().PadRight(1, ' ')
   + "," + row[4].ToString().PadRight(30, ' ') + "," + row[5].ToString().PadRight(15, ' ') + "," + row[6].ToString().PadRight(1, ' ') + "," + row[7].ToString().PadRight(4, ' ')
   + "," + row[8].ToString().PadRight(30, ' ') + "," + row[9].ToString().PadRight(6, ' ') + "," + row[10].ToString().PadRight(30, ' ') + "," + row[11].ToString().PadRight(30, ' ')
   + "," + row[12].ToString().PadRight(30, ' ') + "," + row[13].ToString().PadRight(30, ' ') + "," + row[14].ToString().PadRight(30, ' ') + "," + row[15].ToString().PadRight(13, ' ')
   + "," + row[16].ToString().PadRight(13, ' ') + "," + row[17].ToString().PadRight(13, ' ') + "," + row[18].ToString().PadRight(13, ' ') + "," + row[19].ToString().PadRight(7, ' ')
   + "," + row[20].ToString().PadRight(1, ' ') + "," + row[21].ToString().PadRight(11, ' ') + "," + row[22].ToString().PadRight(1, ' ') + "," + row[23].ToString().PadRight(13, ' ')
   + "," + row[24].ToString().PadRight(8, ' ') + "," + row[25].ToString().PadRight(39, ' '));
}

using (StreamWriter outFile = new StreamWriter(mypath + @"\CCC.txt")) outFile.Write(sb.ToString());
myConnection.Close();

Class1和Class2都访问完全相同的对象,而Class3访问该对象的全新实例。

像Chetan Kinger一样宣告豆子的最后方式解释与自动装配相同,因为生命周期由春季管理,唯一的区别在于豆子的位置。

当我第一次遇到春天时,这个网站给了我很多帮助(可能对你有帮助)http://www.tutorialspoint.com/spring/index.htm